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

10,950

This seems to work for me:

import subprocess

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

p.wait()

print 'done'
Share:
10,950
ritratt
Author by

ritratt

Updated on June 04, 2022

Comments

  • ritratt
    ritratt almost 2 years

    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
    ritratt over 11 years
    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 :(
  • AndiDog
    AndiDog over 11 years
    Any way to get the right exit code (ERRORLEVEL) from the batch file? I always get 0.
  • martineau
    martineau over 11 years
    @AndiDog: Using start makes getting the exit code difficult, but it might be possible to instead Popen() something like what's in this answer and retrieve it through the p.returncode attribute following the p.wait().