如何使用 Python 在后台运行 DOS 批处理文件



如何使用Python在后台运行DOS批处理文件?

我有一个测试.bat文件在说 C:\
现在,我想在后台使用 python 运行这个 bat 文件,然后我想返回到 python 命令行。

我使用 python 命令行中的subprocess.call('pathtotest.bat')运行批处理文件。它在与 python 命令行相同的窗口中运行批处理文件。

如果仍然不清楚/TL。博士-

发生了什么事情:

>>>subprocess.call('C:test.bat')
(Running test.bat. Can't use python in the same window)

我想要什么:

>>>subprocess.call('C:test.bat')
(New commandline window created in the background where test.bat runs in parallel.)
>>>

这似乎对我有用:

import subprocess
p = subprocess.Popen(r'start cmd /c C:test.bat', shell=True)
p.wait()
print 'done'

subprocess.call的文档说

运行 args 描述的命令。 等待命令完成,然后返回返回码属性。

在您的情况下,您不希望等待命令完成再继续程序,因此请改用subprocess.Popen

subprocess.Popen('C:test.bat')

我会使用

subprocess.Popen("test.bat", creationflags=subprocess.CREATE_NEW_CONSOLE)
#subprocess.call("ls")
#etc...

因此,您可以继续在同一文件中调用其他命令,在单独的cmd窗口上运行"test.bat"。

最新更新