使用subprocess.run在Windows上运行进程

时间:2016-11-08 16:53:15

标签: python subprocess windows-shell

我希望通过Python运行以下非常冗长的shell命令:

C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe "E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat" pc\ndf\patchable\gfx\everything.ndfbin TAmmunition

当我从Windows shell中按原样运行它时,它按预期工作。

然而,当我试图通过Python subprocess.run做同样的事情时,它并不喜欢它。以下是我的意见:

import subprocess
comm = [r'C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe "E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat" pc\ndf\patchable\gfx\everything.ndfbin TAmmunition']
subprocess.run(comm, shell=True)

这是我的输出:

The directory name is invalid.
Out[5]: CompletedProcess(args=['C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe "E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat" pc\\ndf\\patchable\\gfx\\everything.ndfbin TAmmunition'], returncode=1)

为什么会这样?

2 个答案:

答案 0 :(得分:3)

间距错误。 subprocess期望一个参数列表,它会为你正确地分隔出来。

comm = ['C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe','E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat','pc\ndf\patchable\gfx\everything.ndfbin','TAmmunition']

您收到错误的原因是因为e:/ steam周围的双引号... 它正在写一个类似于shell的东西:

c:/users/alex/desktop/tableexporter/wgtableexporter.exe \"E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat\" pc\ndf\patchable\gfx\everything.ndfbin TAmmunition

答案 1 :(得分:1)

间距不正确,但使用os.system()不需要您更改间距。

这应该有效:

import os
os.system("""C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe      "E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat" pc\ndf\patchable\gfx\everything.ndfbin TAmmunition""")

但是如果你想使用子进程(这是更好的)

import subprocess
comm = ['C:/Users/Alex/Desktop/tableexporter/WGTableExporter.exe','E:/Steam (Games Installed Directly to Hard Drive)/steamapps/common/Wargame Red Dragon/Data/WARGAME/PC/430000626/NDF_Win.dat','pc\ndf\patchable\gfx\everything.ndfbin TAmmunition']
subprocess.run(comm, shell=True)