簡體   English   中英

帶有Pygame的Python subprocess.Popen(),如何告訴Pygame等到子進程完成

[英]Python subprocess.Popen() with Pygame , how to tell Pygame wait untill subprocess is done

我有太多Pygame用戶遇到的主要問題,我想從Pygame中的用戶那里獲取輸入。 我可能檢查了Internet中的所有信息,包括stackoverflow,沒有任何解決方法。

因此,我決定提出一個解決方案,我創建了另一個Python腳本(將其轉換為.exe,以便子進程可以打開它),以便在Pygame運行之前向用戶詢問問題,然后該腳本將用戶的數據保存到.txt文件中(例如一個數據庫)。然后在Pygame中打開該.txt文件並獲取數據。 從理論上講,它正在工作,但是問題是,我必須告訴Pygame,子進程正在處理時,請等待它。 這就是我可以避開諸如IndexError等錯誤的方法。因為我使用的是readlines() ,直到關閉.exe文件,否則Pygame必須等待;否則。 readlines()列表形式提供數據,並正常拋出IndexError。 因此,Pygame必須等到我將數據放入該.exe文件中。 讓我解釋一下我的代碼;

這是從用戶那里獲取數據的腳本(我已經將其轉換為exe,因此子進程可以打開):

#!/usr/bin/env python
# -*-coding:utf-8-*-

while True:
    user=input("Please enter your name: ")
    try:
        user_age=int(input("Please enter your age: "))
    except ValueError:
        print ("Invalid characters for 'age', try again.")
        continue
    ask_conf=input("Are you confirm these informations?(Y/N): ")
    if ask_conf.lower()=="y":
        with open("informations.txt","w") as f: #create the file
            f.write(user+"\n")
            f.write(str(user_age))
        break
    else:
        continue

然后,在Pygame中,我正在打開此.exe文件,但是Pygame不會等待,通常我會遇到錯誤。

pygame.init()
subprocess.Popen(["wtf.exe"]) #the exe file that taking data from user 
                              #and saving it in "informations.txt"
#codes..
....
....
author = pygame.font.SysFont("comicsansms",25)
with open("informations.txt") as f:
    rd=f.readlines()
author1 = author.render("{}".format(rd[0][0:-1]),True,blue) #Pygame won't wait 
                                                            #so getting IndexError here
age = pygame.font.SysFont("comicsansms",25)
age1 = age.render("{}".format(rd[1]),True,blue)
...
...
...
gameDisplay.blit(author1,(680,15))
gameDisplay.blit(age1,(720,40))

這個方法幾乎可以用了,我以為我終於在Pygame中解決了這個輸入問題。但是我不知道如何告訴Pygame,等到我用完.exe文件后再處理代碼。

使用溝通方法:

與進程交互:將數據發送到stdin。 從stdout和stderr讀取數據,直到到達文件末尾。 等待進程終止。 可選輸入參數應該是要發送給子進程的字符串,如果沒有數據要發送給子進程,則為None。

因此,這是執行此操作的代碼:

process = subprocess.Popen(["wtf.exe"])
# block until process done
output, errors = process.communicate()

編輯:

正如@Padraic所建議的,您可以使用check_call ,它在失敗時會提供更多信息

try:
    subprocess.check_call([’wtf.exe’])
except subprocess.CalledProcessError:
    pass # handle errors in the called executable
except OSError:
    pass # executable not found

另一個選擇是call

運行args描述的命令。 等待命令完成,然后返回returncode屬性。

所以像這樣:

returncode = subprocess.call(["wtf.exe"])

而且,如果您不關心數據,而只希望返回代碼查看是否發生了不良情況,也可以使用wait 但是文檔說您應該更喜歡communicate

警告:當使用stdout = PIPE和/或stderr = PIPE時,這將死鎖,並且子進程會向管道生成足夠的輸出,從而阻塞等待OS管道緩沖區接受更多數據的等待。 使用communication()可以避免這種情況。

暫無
暫無

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

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