2012-10-09 79 views
2

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

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

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

如果还不清楚/ TL.DR-

正在发生的事情:

>>>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.) 
>>> 
+0

顺便说一句,当你想要字符串中的文字反斜线字符(例如指定Windows文件路径)时,您必须将它们加倍为“C:\\ test.bat”,或者通过在字符串前加字母来指示原始字符串格式在'r'C:\ test.bat'这样的第一个引号之前的'r'。请参阅文档中的[字符串文字](http://docs.python.org/reference/lexical_analysis.html#string-literals)。 – martineau

回答

4

这似乎为我工作:

import subprocess 

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

p.wait() 

print 'done' 
+0

任何方式从批处理文件中获得正确的退出代码(ERRORLEVEL)?我总是得到0. – AndiDog

+0

@AndiDog:使用'start'可以让退出代码变得困难,但是它可以替代'Popen()',就像[this](http://stackoverflow.com/a/3119934/355230)中的内容一样回答并检索它'p.wait()'后面的'p.returncode'属性。 – martineau

0

subprocess.call文档说

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

你的情况,你不想等待命令完成,你继续你的程序之前,所以用subprocess.Popen代替:

subprocess.Popen('C:\test.bat') 
+0

它仍然没有在后台打开。唯一的区别是,当我按Ctrl + C它退出python而不是返回到Python命令行:( – ritratt

0

我会用

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

所以日您可以继续在同一个文件中调用其他命令,让“test.bat”在单独的cmd窗口中运行。