我想要这样的代码:
if True:
run('ABC.PY')
else:
if ScriptRunning('ABC.PY):
stop('ABC.PY')
run('ABC.PY'):
基本上,我想根据某些条件运行一个文件,例如abc.py
。我想停止它,然后从另一个python脚本再次运行它。有可能吗?
我正在使用Windows。
答案 0 :(得分:5)
您可以使用python Popen对象在子进程中运行进程
因此run('ABC.PY')
将是p = Popen("python 'ABC.PY'")
if ScriptRunning('ABC.PY)
将是if p.poll() == None
stop('ABC.PY')
将是p.kill()
答案 1 :(得分:2)
这是您要实现的目标的非常基本的示例
请签出子流程。打开文档以微调您运行脚本的逻辑
import subprocess
import shlex
import time
def run(script):
scriptArgs = shlex.split(script)
commandArgs = ["python"]
commandArgs.extend(scriptArgs)
procHandle = subprocess.Popen(commandArgs, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
return procHandle
def isScriptRunning(procHandle):
return procHandle.poll() is None
def stopScript(procHandle):
procHandle.terminate()
time.sleep(5)
# Forcefully terminate the script
if isScriptRunning(procHandle):
procHandle.kill()
def getOutput(procHandle):
# stderr will be redirected to stdout due "stderr=subprocess.STDOUT" argument in Popen call
stdout, _ = procHandle.communicate()
returncode = procHandle.returncode
return returncode, stdout
def main():
procHandle = run("main.py --arg 123")
time.sleep(5)
isScriptRunning(procHandle)
stopScript(procHandle)
print getOutput(procHandle)
if __name__ == "__main__":
main()
您应该了解的一件事是stdout = subprocess.PIPE。 如果您的python脚本输出很大,则管道可能会溢出,导致脚本阻塞,直到通过句柄调用.communicate为止。 为了避免这种情况,将文件句柄传递给stdout,就像这样
fileHandle = open("main_output.txt", "w")
subprocess.Popen(..., stdout=fileHandle)
这样,python进程的输出将被转储到文件中(为此您也必须修改getOutput()函数)
答案 2 :(得分:1)
import subprocess
process = None
def run_or_rerun(flag):
global process
if flag:
assert(process is None)
process = subprocess.Popen(['python', 'ABC.PY'])
process.wait() # must wait or caller will hang
else:
if process.poll() is None: # it is still running
process.terminate() # terminate process
process = subprocess.Popen(['python', 'ABC.PY']) # rerun
process.wait() # must wait or caller will hang