【问题标题】:Run a .bat program in the background on Windows在 Windows 的后台运行 .bat 程序
【发布时间】:2011-09-20 20:25:15
【问题描述】:

我正在尝试在新窗口中运行.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

【问题讨论】:

标签: python process background batch-file subprocess


【解决方案1】:

使用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.

【讨论】:

    【解决方案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"
    

    【讨论】:

    • 这只是python 2.7吗?
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:
      import subprocess
      proc = subprocess.Popen(['/path/script.bat'], 
                              stdout=subprocess.PIPE, 
                              stderr=subprocess.STDOUT)
      

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

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

      proc.wait()
      

      【讨论】:

        猜你喜欢
        • 2021-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-18
        相关资源
        最近更新 更多