繁体   English   中英

如何从另一个 python 脚本运行和停止 python 脚本?

[英]How to run & stop python script from another python script?

我想要这样的代码:

if True:
    run('ABC.PY')
else:
    if ScriptRunning('ABC.PY):
       stop('ABC.PY')
    run('ABC.PY'):

基本上,我想运行一个文件,比如说abc.py ,并且基于一些条件。 我想停止它,然后从另一个 python 脚本再次运行它。 可能吗?

我正在使用 Windows。

您可以使用 python Popen对象在子进程中运行进程

所以run('ABC.PY')将是p = Popen("python 'ABC.PY'")

if ScriptRunning('ABC.PY)将是if p.poll() == None

stop('ABC.PY')将是p.kill()

这是您要实现的目标的一个非常基本的示例

请检查 subprocess.Popen 文档以微调您运行脚本的逻辑

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 脚本具有非常大的 output,则管道可能会溢出,从而导致您的脚本阻塞,直到通过句柄调用通信。 为避免这种情况,请将文件句柄传递给标准输出,如下所示

fileHandle = open("main_output.txt", "w")
subprocess.Popen(..., stdout=fileHandle)

这样,python 进程的 output 将被转储到文件中。(为此,您也必须修改 getOutput() function)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM