gpt4 book ai didi

python - 在 Windows 的后台运行 .bat 程序

转载 作者:太空狗 更新时间:2023-10-30 00:57:33 30 4
gpt4 key购买 nike

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

关于python - 在 Windows 的后台运行 .bat 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6448217/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com