【发布时间】:2019-10-05 23:19:42
【问题描述】:
我目前正在使用多处理,因此我可以在运行其他代码时获取用户输入。这个版本的代码对我来说在 ubuntu 19.04 上运行,但对我的朋友来说它在 windows 上不起作用。
import getch
import time
from multiprocessing import Process, Queue
prev_user_input = ' '
user_input = ' '
# Getting input from the user
queue = Queue(1)
def get_input():
char = ' '
while char != 'x':
char = getch.getch()
queue.put(char)
# Starting the process that gets user input
proc = Process(target=get_input)
proc.start()
while True:
# Getting the users last input
while not queue.empty():
user_input = queue.get()
# Only print user_input if it changes
if prev_user_input != user_input:
print(user_input)
prev_user_input = user_input
time.sleep(1/10)
如何让这段代码在 Windows 上运行?
此外,用户输入滞后一个输入。如果用户按下一个按钮,它只会在他按下另一个按钮后打印。有关如何解决此问题的解决方案也会有所帮助。
编辑 1: 他使用的是 Python 3.7.4,而我使用的是 3.7.3。
我按照建议尝试了这段代码
import msvcrt
import time
from multiprocessing import Process, Queue
prev_user_input = ' '
user_input = ' '
# Getting input from the user
queue = Queue(1)
def get_input():
char = ' '
while char != 'x':
char = msvcrt.getch()
queue.put(char)
# Starting the process that gets user input
if __name__ == '__main__':
proc = Process(target=get_input)
proc.start()
while True:
# Getting the users last input
while not queue.empty():
user_input = queue.get()
# Only print user_input if it changes
if prev_user_input != user_input:
print(user_input)
prev_user_input = user_input
time.sleep(1/10)
但是没有打印任何字符。
编辑 2:
我在 Windows 上使用 msvcrt 模块,在 ubuntu 上使用 getch 模块。很抱歉没有在帖子前面说清楚。
【问题讨论】:
-
尝试在
# Starting the process that gets user input行之前添加一个if __name__ == '__main__':行——同时缩进该行后面的所有代码。在“安全导入主模块”小节中,Programming Guidelines 中的multiprocessing模块解释了这样做的必要性。 -
你在每台机器上使用了哪些版本的python?
-
@martineau 我试过这样做。现在程序不会崩溃,但它不会显示与在 linux 中相同的行为,即打印字符。
-
@AnnKilzer 我正在使用 3.7.3,他正在使用 3.7.4。
-
我不明白使用
msvcrt.getch()是如何在 Windows 以外的任何东西上工作的——但你声称它在 ubuntu 上可以工作。
标签: python python-3.x linux windows multiprocessing