如何使用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.)
>>>
順便說一句,當你想要字符串中的文字反斜線字符(例如指定Windows文件路徑)時,您必須將它們加倍爲「C:\\ test.bat」,或者通過在字符串前加字母來指示原始字符串格式在'r'C:\ test.bat'這樣的第一個引號之前的'r'。請參閱文檔中的[字符串文字](http://docs.python.org/reference/lexical_analysis.html#string-literals)。 – martineau