繁体   English   中英

Python:如何从另一个脚本终止一个脚本的功能

[英]Python: how to terminate a function of a script from another script

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

我试图与ps一起使用不同的bash命令(使用os.system),但是它给我的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

您可以通过在另一个过程中获得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() 然后,该过程将被终止,并继续执行下一步操作。

希望这可以帮助。

暂无
暂无

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

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