Python: 我开始一个新线程,我的程序暂停直到线程结束

Python: I start a new thread, and my program pauses until the thread is finished

当我尝试启动一个新线程时,我的整个程序停止,直到该线程的函数完成。我正在尝试让线程在我的程序同时运行时启动并继续。

代码:

def do_python(string):
    while True:
        exec(string, globals())
        time.sleep(0.1)

getKeyThread = threading.Thread(target=do_python("key = cpc.get_key()"), daemon=True).start()

time.sleep(0.2)

while True:

    if key == 9:
        print("Tab pressed.")
        exit()

我已经导入了所有需要的模块,所以这不是问题所在。此处使用的任何未定义的函数都已在别处定义并且工作得很好。我没有在这里包含我的整个程序,因为它太大而无法粘贴到这里。

通过

do_python("key = cpc.get_key()")

你实际上是在你的主线程中调用do_python函数(它有一个无限循环并且永远不会停止运行)。由于该函数从不 return 任何东西,它只会永远保持 运行 。如果它做了 return 某些事情,除非在可调用对象中 returned 什么,否则你可能会得到一个错误。

参数target requires a callable,所以你必须将你的函数传递给它

getKeyThread = threading.Thread(target=do_python, args=some_args, daemon=True).start()