在Windows后台运行.bat程序

6 投票
4 回答
8798 浏览
提问于 2025-04-16 20:07

我想在一个新窗口里运行一个 .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 个回答

1

在Windows系统中,后台运行的程序叫做“服务”。如果你想了解如何用Python创建一个Windows服务,可以看看这个问题:创建一个Python Win32服务

2

看起来你想要使用“os.spawn*”,这个功能在Windows上相当于os.fork。通过一些搜索,我找到了这个例子:

# 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"
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.

撰写回答