简体   繁体   English

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

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

I have a script main.py which called a function fun from a library. 我有一个脚本main.py ,它从库中调用了一个函数fun I want to exit only from fun continuing the script main.py , using for this purpose another script kill_fun.py . 我只想退出继续执行脚本main.py fun ,为此使用了另一个脚本kill_fun.py

I tried to use different bash commands (using os.system) with ps , but the pid it gives me is referred only to main.py . 我试图与ps一起使用不同的bash命令(使用os.system),但是它给我的pid仅指向main.py

Example: 例:

-main.py -main.py

from lib import fun

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

-lib.py -lib.py

def fun():
    do_something_of_long_time

-kill_fun.py -kill_fun.py

if __name__ == '__main__':
    kill_only_fun

You can do so by run fun in a different process. 您可以通过在另一个过程中获得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")

to kill fun , simply echo 'Y' > kill.txt 要消灭fun ,只需echo 'Y' > kill.txt

or you can write a python script to write the file as well. 或者,您也可以编写python脚本来编写文件。

Explain The idea is to start fun in a different process. 解释这个想法是从另一个过程开始fun p is a process handler that you can control. p是您可以控制的流程处理程序。 And then, we put a loop to check file kill.txt to see if kill command 'Y' is in there. 然后,我们放置一个循环来检查文件kill.txt以查看是否存在kill命令'Y'。 If yes, then it call p.terminate() . 如果是,则调用p.terminate() The process will then get killed and continue to do next things. 然后,该过程将被终止,并继续执行下一步操作。

Hope this helps. 希望这可以帮助。

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

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