Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a .bat program in the background on Windows

I am trying to run a .bat file (which acts as a simulator) in a new window, so it must always be running in the background. I think that creating a new process is the only option that I have. Basically, I want my code to do something like this:

    def startSim:
        # open .bat file in a new window
        os.system("startsim.bat")
        # continue doing other stuff here
        print("Simulator started")

I'm on Windows so I can't do os.fork.

like image 349
Vikram Avatar asked Jun 23 '11 00:06

Vikram


1 Answers

Use subprocess.Popen (not tested on Windows, but should work).

import subprocess

def startSim():
    child_process = subprocess.Popen("startsim.bat")

    # Do your stuff here.

    # You can terminate the child process after done.
    child_process.terminate()
    # You may want to give it some time to terminate before killing it.
    time.sleep(1)
    if child_process.returncode is None:
        # It has not terminated. Kill it. 
        child_process.kill()

Edit: you could also use os.startfile (Windows only, not tested too).

import os

def startSim():
    os.startfile("startsim.bat")
    # Do your stuff here.
like image 184
Artur Gaspar Avatar answered Nov 04 '22 01:11

Artur Gaspar