在Windows上的后台运行.bat程序

Vik*_*ram 5 python subprocess background process batch-file

我正在尝试.bat在新窗口中运行文件(充当模拟器),因此该文件必须始终在后台运行。我认为创建新流程是我唯一的选择。基本上,我希望我的代码执行以下操作:

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

我在Windows上无法使用os.fork

Pat*_*ini 2

看起来你想要“os.spawn*”,它似乎等同于 os.fork,但对于 Windows。一些搜索出现了这个例子:

# File: os-spawn-example-3.py

import os
import string

if os.name in ("nt", "dos"):
    exefile = ".exe"
else:
    exefile = ""

def spawn(program, *args):
    try:
        # check if the os module provides a shortcut
        return os.spawnvp(program, (program,) + args)
    except AttributeError:
        pass
    try:
        spawnv = os.spawnv
    except AttributeError:
        # assume it's unix
        pid = os.fork()
        if not pid:
            os.execvp(program, (program,) + args)
        return os.wait()[0]
    else:
        # got spawnv but no spawnp: go look for an executable
        for path in string.split(os.environ["PATH"], os.pathsep):
            file = os.path.join(path, program) + exefile
            try:
                return spawnv(os.P_WAIT, file, (file,) + args)
            except os.error:
                pass
        raise IOError, "cannot find executable"

#
# try it out!

spawn("python", "hello.py")

print "goodbye"
Run Code Online (Sandbox Code Playgroud)