Python Forum

Full Version: Wait for command within a process
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm attempting to set up a process which listens for commands. Eventually this will be implemented with TCP/UDP and MODBUS, but for now I am trying to get it to work from within a process. The syntax is simple: I am starting a process with the target being the listenForCommand() function. This function is supposed to wait for input from the user using the input() function.
The program does not, however, wait for input. It instead throws an EOFError: EOF when reading a line. However, if I run the listenForCommand() function by itself, without it being executed from a process, then it works fine. Somehow the process is not allowing input() to wait for input. Here's some code, and output:

from multiprocessing import Process

def listenForCommand():
    # Capture user input
    print("-1:Exit 1:Home 2:LoadCard:")
    selection = int(input())
    
    # Execute selected action
    while selection != -1:
        if(selection == 1):
            p1 = Process(target=Routines.home, args=(VacuumTrayTravel,Main_Registry))
        elif(selection == 2):
            p1 = Process(target=Routines.loadCard)
        
        p1.start()
        p1.join()
        
        # Prompt user again
        print("-1:Exit 1:Home 2:LoadCard:")
        selection = int(input())

# Main execution starts here
Process(target=listenForCommand).start()
Output:
-1:Exit 1:Home 2:LoadCard: Process Process-1: Traceback (most recent call last): File "/usr/lib/python3.5/multiprocessing/process.py", line 249, in _bootstrap self.run() File "/usr/lib/python3.5/multiprocessing/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "/home/debian/RMI/src/Main.py", line 158, in listenForCommand selection = int(input()) EOFError: EOF when reading a line
OR, this is how I am running it standalone:
# Main execution starts here
listenForCommand()
Output:
-1:Exit 1:Home 2:LoadCard: 1 [Code executes] -1:Exit 1:Home 2:LoadCard
Solution:
multiprocessing disables the stdin when it starts a process, therefore input() cannot be used.

https://stackoverflow.com/questions/4283...ing-a-line
Quote:The multiprocessing module doesn't let you read stdin. That makes sense generally because mixing stdin readers from multiple children is a risky business. In fact, digging into the implementation, multiprocessing/process.py explicitly sets stdin to devnull:

sys.stdin.close()
sys.stdin = open(os.devnull)


I've instead swapped to using a Thread to listen for the input:
from threading import Thread

# Main execution starts here
Thread(target=listenForCommand).start()