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