开发者社区> 问答> 正文

如何为Windows重写此多处理代码?

我当前正在使用多处理,因此我可以在运行其他代码时获得用户输入。此版本的代码对我来说在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)

但是没有字符被打印。

展开
收起
祖安文状元 2020-01-07 14:20:27 410 0
1 条回答
写回答
取消 提交回答
  • 以下内容适用于Windows。它包含了我在您的问题下的评论中建议的所有更改,包括最后一个有关单独的内存空间的更改。

    使用ubuntu的版本,类似的东西也应该可以在ubuntu下工作getch(),尽管我尚未对其进行测试。on主进程创建Queue并将其作为参数传递给get_input()目标函数,因此它们都使用同一对象交换数据。

    我还返回了将其转换为(1个字符)Unicode UTF-8字符串decode()的bytes对象msvcrt.getch()。

    import msvcrt
    import time
    from multiprocessing import Process, Queue
    
    prev_user_input = ' '
    user_input = ' '
    
    
    def get_input(queue):
        char = ' '
        while char != b'x':
            char = msvcrt.getch()
            queue.put(char.decode())  # Convert to utf-8 string.
    
    if __name__ == '__main__':
        # Getting input from the user.
        queue = Queue(1)
    
        # Starting the process that gets user input.
        proc = Process(target=get_input, args=(queue,))
        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)
    
    2020-01-07 14:20:39
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
《云服务器运维之Windows篇》 立即下载
TAKING WINDOWS 10 KERNEL 立即下载
ECS运维指南之Windows系统诊断 立即下载