簡體   English   中英

Python子進程通信掛起

[英]Python subprocess communicate hangs

我知道這是一個經常被問到的問題,我已經嘗試了可以​​在這里和其他站點上找到的任何解決方案,但不能解決我的問題。 我的困境如下(在Windows上):

我有一個主腳本(main.py),在其中通過Popen調用另一個腳本(sniffer.py)創建一個子進程。 之后,我要在main.py中做一些事情,最后要向該子進程發送一個字符,以完成sniffer.py中的無限循環,最后完成整個子進程。

main.py

process = Popen(["python", "sniffer.py", receiverIP, senderIP, "udp", path],stdin=PIPE)
#do some stuff
process.communicate('terminate')

嗅探器

def check(done):
    while True:
        if sys.stdin.read() == 'terminate':
            done = True
            break
def sniff(someparams):
    done = False
    input_thread = threading.Thread(target=check, args=(done,))
    input_thread.daemon = True
    input_thread.start()
    while True:
        #do some stuff
        if done:
            break

我也嘗試過將通訊調用與stdin.write結合使用,但沒有效果。

注意:我注意到,在我的communication()調用之后,sniffer.py中的while循環不會繼續(整個腳本只是掛起)

subprocess無關。

更改doneTrue本地。 您必須全局定義它,以使最后一個循環正確退出。

done = False

def check():
    global done
    while True:
        if sys.stdin.read() == 'terminate':
            done = True
            break
def sniff(someparams):
    global done
    done = False
    input_thread = threading.Thread(target=check)
    input_thread.daemon = True
    input_thread.start()
    while True:
        #do some stuff
        if done:
            break

暫無
暫無

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

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