3

I'm trying to create a child process that can take input through raw_input() or input(), but I'm getting an end of liner error EOFError: EOF when asking for input.

I'm doing this to experiment with multiprocessing in python, and I remember this easily working in C. Is there a workaround without using pipes or queues from the main process to it's child ? I'd really like the child to deal with user input.

def child():
    print 'test' 
    message = raw_input() #this is where this process fails
    print message

def main():
    p =  Process(target = child)
    p.start()
    p.join()

if __name__ == '__main__':
    main()

I wrote some test code that hopefully shows what I'm trying to achieve.

Alexander Pope
  • 1,134
  • 1
  • 12
  • 22

1 Answers1

4

My answer is taken from here: Is there any way to pass 'stdin' as an argument to another process in python?

I have modified your example and it seems to work:

from multiprocessing.process import Process
import sys
import os

def child(newstdin):
    sys.stdin = newstdin
    print 'test' 
    message = raw_input() #this is where this process doesn't fail anymore
    print message

def main():
    newstdin = os.fdopen(os.dup(sys.stdin.fileno()))
    p =  Process(target = child, args=(newstdin,))
    p.start()
    p.join()

if __name__ == '__main__':
    main()
Community
  • 1
  • 1
ZalewaPL
  • 1,104
  • 1
  • 6
  • 14
  • does this work on your end ? I get *ValueError: I/O operation on closed file* – Alexander Pope Dec 12 '12 at 09:21
  • Yes it does. Maybe the behavior is OS dependant. What OS are you on? I'm on Linux. – ZalewaPL Dec 12 '12 at 10:02
  • Windows 8, i guess this is problem – Alexander Pope Dec 12 '12 at 10:05
  • This probably won't help but it's worth a try: check what happens if you pass the return value from os.dup() as the newstdin and move os.fdopen() to child() function. – ZalewaPL Dec 12 '12 at 10:10
  • 1
    That works, somewhat, but the child now can't exit from raw_input(), and the whole script strangely exists after 3~4 seconds, and none of the print statements work. – Alexander Pope Dec 12 '12 at 10:48
  • Disregarding the answer to your actual question I'd reconsider what you said: "I'd really like the child to deal with user input." Personally I find this approach strange. It's simply not something that I'd do and expect it to work correctly. Perhaps you should revise your design. – ZalewaPL Dec 12 '12 at 15:14
  • 1
    I'm not building a large application here, I was trying to do this in order to better grasp python and it's multiprocessing library. Thank you for your time and advice though ! – Alexander Pope Dec 12 '12 at 19:08