即使用戶沒有寫任何東西,我也需要退出包含輸入陳述句的回圈。它也從行程接收引數,并且必須立即評估內容。像這樣的東西:
import multiprocessing
def my_function (my_queue):
var = ""
#### some code which finally puts something in the queue ###
my_queue.put(var)
def main():
my_queue = multiprocessing.Queue()
p1 = multiprocessing.Process (target=my_function, args =(my_queue,))
p1.daemon = True
p1.start()
my_var = ""
while (my_queue.empty() is True and my_var == ""):
my_var = input ("enter a parameter for my_var: ")
#### code that evaluates the queue and the input as appropiate
## I want to exit the loop if there's something in the queue even if the user hasn't written anything
這當然行不通。主回圈堆疊在輸入部分。有任何想法嗎?我正在使用 Windows。謝謝大家!
uj5u.com熱心網友回復:
asyncio通過濫用模塊,一個可能是跨平臺的答案。
我不完全理解我做了什么,而且我確信這是錯誤的形式,但我創建了兩個并發任務,一個等待輸入,一個檢查佇列中的值并引發 InterruptError。由于 return_when='FIRST_EXCEPTION' 設定,這兩個函式都必須引發例外。我通過例外回傳了用戶輸入,因為該函式永遠不會回傳。
import asyncio
import multiprocessing
import time
from aioconsole import ainput
def my_function(queue):
time.sleep(3)
queue.put(5)
async def my_loop(queue):
while True:
await asyncio.sleep(0.1)
if not queue.empty():
raise InterruptedError
async def my_exceptional_input():
text = await ainput("Enter input:")
raise InterruptedError(text)
async def main():
queue = multiprocessing.Queue()
p = multiprocessing.Process(target=my_function, args=(queue,))
p.start()
task1 = asyncio.create_task(my_exceptional_input())
task2 = asyncio.create_task(my_loop(queue))
result = await asyncio.wait([task1, task2], return_when='FIRST_EXCEPTION')
try:
task2.result()
except asyncio.exceptions.InvalidStateError:
text = str(task1.exception())
except InterruptedError:
text = ""
print('Doing stuff with input %s...' % text)
if __name__ == '__main__':
asyncio.run(main())
編輯:使用“FIRST_EXCEPTION”很愚蠢。我可以像這樣使用“FIRST_COMPLETED”:
import asyncio
import multiprocessing
import time
from aioconsole import ainput
def my_function(queue):
time.sleep(3)
queue.put(5)
async def my_loop(queue):
while True:
await asyncio.sleep(0.1)
if not queue.empty():
break
async def main():
queue = multiprocessing.Queue()
p = multiprocessing.Process(target=my_function, args=(queue,))
p.start()
task1 = asyncio.create_task(ainput("Enter text:"))
task2 = asyncio.create_task(my_loop(queue))
result = await asyncio.wait([task1, task2], return_when='FIRST_COMPLETED')
try:
text = task1.result()
q = ""
except asyncio.exceptions.InvalidStateError:
text = ""
q = queue.get()
print('Doing stuff with input %s/%s...' % (text, q))
if __name__ == '__main__':
asyncio.run(main())
uj5u.com熱心網友回復:
試試這個:我們使用 將信號從子行程發送到父行程os.kill,這會引發我們捕獲的例外以轉義input函式。
import multiprocessing
import signal
import time
import os
def my_function (my_queue, pid):
var = ""
#### some code which finally puts something in the queue ###
time.sleep(3)
my_queue.put(var)
os.kill(pid, signal.SIGUSR1)
def interrupted(*args):
print('Item added to queue before user input completed.')
raise InterruptedError
def main():
my_queue = multiprocessing.Queue()
p1 = multiprocessing.Process (target=my_function, args =(my_queue,
os.getpid()))
# p1.daemon = True
p1.start()
my_var = ""
try:
signal.signal(signal.SIGUSR1, interrupted)
while (my_queue.empty() is True and my_var == ""):
my_var = input ("enter a parameter for my_var: ")
except InterruptedError:
pass
print('Processing results...')
#### code that evaluates the queue and the input as appropiate
## I want to exit the loop if there's something in the queue even if the user hasn't written anything
if __name__ == '__main__':
main()
上面的代碼只適用于 Unix。我不知道以下代碼是否可以跨平臺作業,但它可能:
import multiprocessing
import signal
import time
import os
def my_function (my_queue, pid):
var = ""
#### some code which finally puts something in the queue ###
time.sleep(3)
my_queue.put(var)
os.kill(pid, signal.SIGINT)
def interrupted(*args):
raise InterruptedError
def main():
print('I am %s!' % os.getpid())
my_queue = multiprocessing.Queue()
p1 = multiprocessing.Process (target=my_function, args =(my_queue,
os.getpid()))
p1.daemon = True
p1.start()
my_var = ""
try:
signal.signal(signal.SIGINT, interrupted)
while (my_queue.empty() is True and my_var == ""):
my_var = input ("enter a parameter for my_var: ")
except InterruptedError:
time.sleep(0.1)
if my_queue.empty():
print('Exiting gracefully...')
return
signal.signal(signal.SIGINT, signal.SIG_DFL)
print('Processing results...')
time.sleep(10)
#### code that evaluates the queue and the input as appropiate
## I want to exit the loop if there's something in the queue even if the user hasn't written anything
if __name__ == '__main__':
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479355.html
