使用 subprocess.run 到 运行 Windows 上的进程

Using subprocess.run to run a process on Windows

我希望通过 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)

为什么会出现这种情况?

间距不对。 subprocess 需要一个参数列表,它将 space 为您正确输出。

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

间距不正确,但是使用 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)