3

How to run a DOS batch file in background using Python?

I have a test.bat file in say C:\
Now, I want to run this bat file using python in the background and then I want to return to the python command line.

I run the batch file using subprocess.call('path\to\test.bat') from the python command line. It runs the batch file in the same window as the python command line.

If still not clear/ TL.DR-

What is happening:

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

What I want:

>>>subprocess.call('C:\test.bat')
(New commandline window created in the background where test.bat runs in parallel.)
>>>
ritratt
  • 1,703
  • 4
  • 25
  • 45
  • BTW, when you want literal backslash characters in strings such as when specifying Windows file paths, you either have to double them like this `'C:\\test.bat'` or indicate raw string format by prefixing the string with an 'r' before the first quote like this `r'C:\test.bat'`. See [string literals](http://docs.python.org/reference/lexical_analysis.html#string-literals) in the documentation. – martineau Oct 09 '12 at 10:01

3 Answers3

6

This seems to work for me:

import subprocess

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

p.wait()

print 'done'
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Any way to get the right exit code (ERRORLEVEL) from the batch file? I always get 0. – AndiDog Oct 14 '12 at 12:14
  • @AndiDog: Using `start` makes getting the exit code difficult, but it _might_ be possible to instead `Popen()` something like what's in [this](http://stackoverflow.com/a/3119934/355230) answer and retrieve it through the `p.returncode` attribute following the `p.wait()`. – martineau Oct 14 '12 at 21:14
0

The documentation for subprocess.call says

Run the command described by args. Wait for command to complete, then return the returncode attribute.

In your case you don't want to wait for the command to complete before you continue your program, so use subprocess.Popen instead:

subprocess.Popen('C:\test.bat')
Mu Mind
  • 10,935
  • 4
  • 38
  • 69
  • It is still not opening in background. The only difference is that when I press Ctrl+C it exits python instead of returning back to Python Command line :( – ritratt Oct 09 '12 at 06:16
0

I would use

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

So then you can keep calling other commands in the same file, having "test.bat" run on a separate cmd window.

Alberto
  • 674
  • 13
  • 25