为什么我的多处理函数的Python函数没有返回任何内容

问题描述 投票:0回答:1

好吧,我只是一个尝试编码的中学生,我想仅使用 python 打印显示来制作一些游戏,并且我需要多处理功能,但在该功能中我有一个输入,所以我需要它不要处于多处理中不然会出错

import multiprocessing
import time
import random

g = "Something from the list: "
def timer(seconds):
print(f"Sleeping for {seconds} second(s)")
time.sleep(seconds)
print( )
return "Done sleeping"
def anything(y):
print(y)
def play(thing,harga):
while True:
t = thing
price = harga\[f"{thing}"\]
y = "-"
h_1 = 54
h = random.randint(0,h_1)
if h == 0:
print(f"{t:{y}\<{h_1+len(t)}}")
ans = input("Do something!:  ")
if ans == thing:
print(f"Great the price is {price} Credits!")
return "True"
else:
h1 = (h_1 - h)
print(f"{y:{y}\<{h}}{t:{y}\<{h1 + len(t)}}")
ans = input("Do something!:  ")
if ans == thing:
print(f"Great the price is {price} Credits!")
return "True"

def idk( ):
time.sleep(0.1)
list = \["Cheese","Pickle"\]
y = random.choice(list)
anything(y)
prilist = {"Cheese": 100,"Pickle":50}
play(y,prilist)
p1 = multiprocessing.Process(target=timer,args=\[3\])
def play1( ):
v = p1.start( )
if v == "Done sleeping":
return "Gagal"
v2 = idk( )
if v2 == "True":
return "True"
p1.join( )
print(play1( ))

好吧,这就是我所做的,我期望当我返回值时,它将结束该函数,但它仍然继续执行其他函数,然后它不打印任何内容

输出:

Sleeping for 3 second(s)

Cheese

\---------------Cheese---------------------------------------Do something!:  Cheese

Great the price is 100 Credits!

None

\[Program finished\]

我真的希望有人能帮助我,如果没有的话也许我只会用 Unity 制作游戏

python function multiprocessing user-input eoferror
1个回答
0
投票

在单独的函数中运行的函数不会直接将值返回给调用者。使用

queues
pipes
从子流程中取回数据。

import multiprocessing
import time
import random
def timer(queue, seconds):
    print(f"Sleeping for {seconds} second(s)")
    time.sleep(seconds)
    queue.put("Done sleeping")
def play():
    choice_list = ["Cheese", "Pickle"]
    price_list = {"Cheese": 100, "Pickle":50}
    while True:
        item = random.choice(choice_list)
        print(f"Current item: {item}")
        ans = input("Do something!: ").strip()
        if ans == item:
            print(f"Great! The price is {price_list[item]} Credits!")
            return True
        else:
            print("Wrong guess, try again!")
def main():
    queue = multiprocessing.Queue()
    timer_process = multiprocessing.Process(target=timer, args=(queue, 3))
    timer_process.start()
    timer_result = queue.get()
    print(f"Timer process returned: {timer_result}")
    game_result = play()
    if game_result:
        print("Congratulations! You guessed correctly!")
    timer_process.join()
if __name__ == "__main__":
    main()
© www.soinside.com 2019 - 2024. All rights reserved.