一直在努力讓它作業,因為我不能return在一個不會結束的 while 回圈中使用。
簡而言之,我在一個函式receive()(無限回圈)中的套接字客戶端中接收到一條訊息,并且需要將該傳入訊息的結果傳遞給main(). 嘗試使用yield,因為我不確定還有什么可以實作這一點。我創建了另一個函式,試圖捕捉yield的receive()功能。
我知道初始訊息到達服務器是因為它輸出訊息,我知道客戶端正在接收服務器的確認訊息,因為它正在列印它。我只是沒有運氣將資料傳遞給main(),所以其余的代碼將無法正常作業。
我對此很陌生,所以我可能做錯了。我應該使用類來更輕松地共享資料,但對它們的掌握還不夠。希望使用 yield 或其他方法可以解決這個問題。
接收功能:
def receive():
while True:
try:
incoming = client.recv(2048).decode(FORMAT)
if 'RECEIVED' in incoming:
confirmation = 'confirmed'
yield confirmation
print(incoming)
except:
print("Connection interrupted.")
client.close()
break
#------------
# also tried
#------------
def receive():
while True:
try:
incoming = client.recv(2048).decode(FORMAT)
if 'RECEIVED:COMPLETE' in incoming:
confirmation = 'confirmed'
else:
confirmation = 'unconfirmed'
yield confirmation
except:
print("Connection interrupted.")
client.close()
break
回傳函式:
def pass_return(passed_return_value):
passed_return_value
主要功能(帶有各種測驗)
def main():
pass_return(receive())
# Bunch of code
if something == True:
send("some message")
time.sleep(.25)
try:
if confirmation == 'confirmed':
# do the business here
#------------
# also tried
#------------
def main():
# Bunch of code
if something == True:
send("some message")
time.sleep(.25)
pass_return(receive())
try:
if confirmation == 'confirmed':
# do the business here
#------------
# also tried
#------------
def main():
r = pass_return(receive())
# Bunch of code
if something == True:
send("some message")
time.sleep(.25)
try:
if r == 'confirmed':
# do the business here
#------------
# even tried
#------------
def main():
# Bunch of code
if something == True:
send("some message")
time.sleep(.25)
r = pass_return(receive())
try:
if r == 'confirmed':
# do the business here
我正在宣告變數confirmationOUTSIDEmain()和receive()(在我的常量所在的檔案的頂部),否則我會得到confirmation is undefined.
如果我print confirmationin main(),它要么不列印,要么不列印None,所以我的猜測是它只是獲取 的初始空值confirmation而不是yield.
# constants above here
confirmation = str()
# code and such
def pass_return(passed_return_value):
passed_return_value
def receive():
#code...
def main():
#code...
if __name__ == '__main__':
main()
uj5u.com熱心網友回復:
請注意,Python 是單執行緒的。如果您的程式除了等待資料從外部源到達套接字并對其做出反應之外什么都不做,那么這將起作用:
def receive():
while True:
try:
incoming = client.recv(2048).decode(FORMAT)
if 'RECEIVED' in incoming:
yield {'status': 'confirmed', 'message': incoming}
else:
yield {'status': 'unconfirmed', 'message': incoming}
except:
print("Connection interrupted.")
client.close()
break
def main():
for message in receive():
print(message)
在這里,該程式的大部分時間將花在client.recv(2048). 這是一個阻塞呼叫。在收到請求的位元組數之前,它不會回傳。在此期間,您的程式中不會發生任何其他事情。
一旦接收到位元組,您就可以yield,并且for內部的回圈main()可以處理資料。完成后,程式流將回傳client.recv(2048)并停留在那里。
如果你想要不同的東西在你的程式發生,同時它也監聽套接字上的資料,您將需要考慮多執行緒,并把這段代碼在后臺執行緒。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/369983.html
標籤:Python 功能 if 语句 变量 while 循环
上一篇:ifelse,is.na并替換
