我尝试在 Python 中做一个线程系统,但我做不到

I try to do a threading system in Python but I can't

我正在尝试制作一个连续运行 while 循环但同时执行另一个正在等待字符串的函数的线程系统。

例如,编写“Hello World”的 while 循环和等待输入内容的函数。

所以我尝试使用此代码,但它不起作用:(

import threading
from time import sleep
import time

data = []

def get_input():
    data.append(input()) # Something akin to this
    return data



input_thread = threading.Thread(target=get_input)
input_thread.start()


while (True):
        print ("Hello World")
        time.sleep(1)

input_thread.join()

if data.pop=="a":
    print ("This message will be writed, only when user typed something")

一些事情。

  • 出栈前检查数组长度
  • 输入线程也必须有循环
  • 输入字符串时需要回车

这是更新后的代码:

import threading
from time import sleep
import time

data = []

def get_input():
    while True:
        data.append(input()) # must press enter to submit

input_thread = threading.Thread(target=get_input)
input_thread.start()

while (True):
    print ("Hello World")
    time.sleep(1)
    if (len(data) and data.pop()=="a"):
        print ("This message will be writed, only when user typed something")
            
input_thread.join()  # never gets here