2012-10-09 76 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窗口中運行。