绝对路径 - Python 3

时间:2015-08-14 05:36:20

标签: python windows python-3.x

我正在编写一个脚本来更改txt文件中的值,然后启动一个应用程序。我只是无法弄清楚如何获得绝对路径。所以调用os.system(path)经常失败,因为我打开的目录中有一个空格。

我试过了:

  • PureWindowsPath('路径&#39)
  • p =路径(路径).resolve()
  • path = os.path.abspath(os.path.dirname(path))

以下是代码的一部分:

def runtime(self):
    """ The container to execute the Class functions. """
    print('This script changes the X axis resolution value for Rocket League.\nThe game will launch after a value is entered.\n')

    path = os.path.abspath(os.path.dirname(open('config.txt').readlines()[1][11:] + 'common\\rocketleague\\Binaries\\Win32\\'))
    print(path)

    inp = input('Enter 1 for 1 Monitor.\nEnter 2 for 2 Monitors.\nEnter C to cancel\n').lower()

    if inp == '1':
        self.replace(self.ConfigFilePath, self.Monitors2, self.Monitors1)
    elif inp == 'c':
        return None
    else:
        self.replace(self.ConfigFilePath, self.Monitors1, self.Monitors2)

    print('Starting Rocket League...')

    os.system('START /D ' + str(path) + ' "" /wait RocketLeague.exe')
    time.sleep(2)

execute.runtime()的输出:

This script changes the X axis resolution value for Rocket League.
The game will launch after a value is entered.

D:\STEAM GAMES\steamapps\common\rocketleague\Binaries\Win32
Enter 1 for 1 Monitor.
Enter 2 for 2 Monitors.
Enter C to cancel
1
Starting Rocket League...
The system cannot find the file GAMES\steamapps\common\rocketleague\Binaries\Win32.

谢谢你看看!

1 个答案:

答案 0 :(得分:0)

有两个问题:

  1. 我需要在命令中加上额外的引号。
  2.   

    OLD:START / D' + str(路径)+' "" /等待RocketLeague.exe

         

    新:START / D " ' + str(路径)+' " "" /等待RocketLeague.exe

    1. 我应该使用子进程模块。
    2. 这是我修改过的功能。它按预期打开了应用程序。

      def runtime(self):
          """ The container to execute the Class functions. """
          print('This script changes the X axis resolution value for Rocket League.\nThe game will launch after a value is entered.\n')
      
          path = os.path.abspath(os.path.dirname(open('config.txt').readlines()[1][11:] + 'common\\rocketleague\\Binaries\\Win32\\'))
      
          inp = input('Enter 1 for 1 Monitor.\nEnter 2 for 2 Monitors.\nEnter C to cancel\n').lower()
      
          if inp == '1':
              self.replace(self.ConfigFilePath, self.Monitors2, self.Monitors1)
          elif inp == 'c':
              return None
          else:
              self.replace(self.ConfigFilePath, self.Monitors1, self.Monitors2)
      
          process = subprocess.Popen('RocketLeague.exe', executable=r'D:\STEAM GAMES\steamapps\common\rocketleague\Binaries\Win32\\RocketLeague.exe')
          time.sleep(2)