Как переписать этот многопроцессорный код для Windows? - PullRequest
0 голосов
/ 06 октября 2019

В настоящее время я использую многопроцессорность, поэтому я могу получить пользовательский ввод при выполнении другого кода. Для меня эта версия кода работает на 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: Я использую модуль msvcrt на окнах и модуль getch на Ubuntu,Извините, что не разъяснил это ранее в посте.

1 Ответ

0 голосов
/ 06 октября 2019

У меня на Windows работает следующее. Он включает в себя все изменения, которые я предложил в моих комментариях к вашему вопросу, в том числе заключительное изменение отдельных пространств памяти.

Нечто подобное должно работать и в Ubuntu, используя его версию getch(), хотя я этого не делалпроверил это. on Основной процесс создает Queue и передает его в качестве аргумента целевой функции get_input(), чтобы они оба использовали один и тот же объект для обмена данными.

Я также decode() * байт объект, возвращаемый из msvcrt.getch() для преобразования его в (1 символ) строку Unicode UTF-8.

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)

обновление

Чтобы скрыть различия ОС и создать кодболее переносимый, вы можете выполнить import, как показано ниже, что также позволит вам определить функцию get_input() более точно, как вы это сделали в коде вашего вопроса:

import os
import time
from multiprocessing import Process, Queue

try:
    import msvcrt
    getch = msvcrt.getwch  # Wide char variant of getch() that returns Unicode.
except ModuleNotFoundError:  # Not Windows OS - no msvcrt.
    from getch import getch

prev_user_input = ' '
user_input = ' '


def get_input(queue):
    char = ' '
    while char != 'x':
        char = getch()
        queue.put(char)


if __name__ == '__main__':
    # For getting input from the user.
    queue = Queue(1)

    # Starting the process that gets user input.

    .
    .
    .
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...