首页 > 解决方案 > Python:如何从另一个脚本终止脚本的功能

问题描述

我有一个脚本,它从库main.py中调用一个函数。fun我只想退出fun继续脚本main.py,为此目的使用另一个脚本kill_fun.py

我尝试使用不同的 bash 命令(使用 os.system)与ps,但它给我的 pid 仅指main.py.

例子:

-main.py

from lib import fun

if __name__ == '__main__':
    try:
        fun()
    except:
        do_something
    do_something_else

-lib.py

def fun():
    do_something_of_long_time

-kill_fun.py

if __name__ == '__main__':
    kill_only_fun

标签: python

解决方案


fun您可以通过在不同的进程中运行来做到这一点。

from time import sleep
from multiprocessing import Process
from lib import fun

def my_fun():
        tmp = 0
        for i in range(1000000):
                sleep(1)
                tmp += 1
                print('fun')
        return tmp

def should_i_kill_fun():
        try:
                with open('./kill.txt','r') as f:
                        read = f.readline().strip()
                        #print(read)
                        return read == 'Y'
        except Exception as e:
                return False

if __name__ == '__main__':
    try:
        p = Process(target=my_fun, args=())
        p.start()
        while p.is_alive():
            sleep(1)
            if should_i_kill_fun():
                p.terminate()
    except Exception as e:
        print("do sth",e)
    print("do sth other thing")

fun_echo 'Y' > kill.txt

或者您也可以编写一个 python 脚本来编写文件。

解释 这个想法是从fun不同的过程开始。p是您可以控制的进程处理程序。然后,我们放一个循环来检查文件kill.txt,看看是否有kill命令'Y'。如果是,则调用p.terminate(). 然后该进程将被终止并继续执行下一步操作。

希望这可以帮助。


推荐阅读