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

时间:2011-06-23 00:53:16

标签: python process background batch-file subprocess

我正在尝试在新窗口中运行.bat文件(充当模拟器),因此它必须始终在后台运行。我认为创建一个新流程是我唯一的选择。基本上,我希望我的代码能做到这样的事情:

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

我在Windows上,所以我无法os.fork

4 个答案:

答案 0 :(得分:3)

使用subprocess.Popen(未在Windows上测试,但应该可以使用)。

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()

编辑:您也可以使用os.startfile(仅限Windows,未经过测试)。

import os

def startSim():
    os.startfile("startsim.bat")
    # Do your stuff here.

答案 1 :(得分: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"

答案 2 :(得分:1)

在Windows上,后台进程称为“服务”。查看有关如何使用Python创建Windows服务的其他问题:Creating a python win32 service

答案 3 :(得分:0)

import subprocess
proc = subprocess.Popen(['/path/script.bat'], 
                        stdout=subprocess.PIPE, 
                        stderr=subprocess.STDOUT)

使用subprocess.Popen()将运行给定的.bat路径(或任何其他可执行文件)。

如果您确实希望等待该过程完成,只需添加proc.wait():

proc.wait()