簡體   English   中英

Python-停止父腳本時如何停止子進程

[英]Python - How to stop child process when the parent script is stoped

父進程停止時如何退出子進程?

以下是我的代碼。

當有KeyboardInterrupt時,我想停止所有執行。

import os, sys
scripts = ["script_1.py","script_2.py"]
try:
    for script in scripts:
        command = 'python ' + script
        os.system(command)
except KeyboardInterrupt:
    os._exit(1)
except Exception as e:
    raise e

由於您嘗試在另一個Python腳本中執行Python腳本,因此讓我們以Pythonic的方式執行此操作,並為importlib.import_module擺脫os.system importlib.import_module

import os
import importlib

scripts = ['script_1.py', 'script_2.py']

for filename in scripts:
    modulename, ext = os.path.splitext(filename)
    importlib.import_module(modulename)

如果您的腳本是這樣的:

if __name__ == '__main__':
     # code here
     print('hello')

它不會工作,因為if __name__ == '__main__':在這里,以確保下的部分if該文件是作為腳本執行(而不是作為一個模塊)將只執行。

因此,在這種情況下,更好的做法是:

script_1.py

def main():
    # code here
    print('hello') 

在主腳本中:

import os
import importlib

scripts = ['script_1.py', 'script_2.py']

for filename in scripts:
    modulename, ext = os.path.splitext(filename)
    module = importlib.import_module(modulename)
    module.main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM