簡體   English   中英

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

[英]Run a .bat program in the background on Windows

我試圖在新窗口中運行.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

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

看起來你想要“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"
import subprocess
proc = subprocess.Popen(['/path/script.bat'], 
                        stdout=subprocess.PIPE, 
                        stderr=subprocess.STDOUT)

使用subprocess.Popen()將運行給定的.bat路徑(或任何其他可執行文件)。

如果你確實希望等待進程完成,只需添加proc.wait():

proc.wait()

在Windows上,后台進程稱為“服務”。 查看有關如何使用Python 創建 Windows服務的另一個問題: 創建python win32服務

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM