簡體   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