Python 在Windows上的后台运行.bat程序
我试图在新窗口中运行Python 在Windows上的后台运行.bat程序,python,process,background,batch-file,subprocess,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") 我在W
.bat
文件(用作模拟器),因此它必须始终在后台运行。我认为创建一个新流程是我唯一的选择。基本上,我希望我的代码可以执行以下操作:
def startSim:
# open .bat file in a new window
os.system("startsim.bat")
# continue doing other stuff here
print("Simulator started")
我在Windows上,因此无法执行操作。fork看起来您想要的是“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"
使用
subprocess.Popen
(未在Windows上测试,但应能正常工作)
编辑:您还可以使用os.startfile
(仅限Windows,未经测试)
在Windows上,后台进程称为“服务”。检查关于如何使用Python创建Windows服务的另一个问题: 使用subprocess.Popen()将运行给定的.bat路径(或任何其他可执行文件) 如果您确实希望等待进程完成,只需添加proc.wait():
看到可能的重复已经读过的关于在windows上制作os.fork的文章,我需要一些我不需要安装模块或程序(cygwin)就能做到的东西。这只是python 2.7吗?
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()
import os
def startSim():
os.startfile("startsim.bat")
# Do your stuff here.
import subprocess
proc = subprocess.Popen(['/path/script.bat'],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
proc.wait()