我目前正在使用多重处理,以便在运行其他代码时获得用户输入。对于我来说,这个版本的代码在ubuntu19.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: 他用的是python3.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)
但没有打印任何字符。你知道吗
以下是我在Windows上的工作。它包含了我在您的问题下的评论中建议的所有更改,包括关于独立内存空间的最后一个更改。你知道吗
类似的东西应该也可以在ubuntu下使用它的
getch()
版本,尽管我还没有测试过它。在主进程上,创建Queue
并将其作为参数传递给get_input()
目标函数,以便它们使用相同的对象交换数据。你知道吗我还
decode()
从msvcrt.getch()
返回的bytes对象,将其转换为(1个字符)Unicode UTF-8字符串。你知道吗更新
要隐藏操作系统差异并使代码更具可移植性,您可以执行如下所示的
import
操作,这也允许您像在问题代码中那样定义get_input()
函数:相关问题 更多 >
编程相关推荐