I'm trying to create a script which is using multiprocessing module with python. The script (lets call it myscript.py) will get the input from another script with pipe.
Assume that I call the scripts like this;
$ python writer.py | python myscript.py And here is the codes;
// writer.py import time, sys def main(): while True: print "test" sys.stdout.flush() time.sleep(1) main() //myscript.py def get_input(): while True: text = sys.stdin.readline() print "hello " + text time.sleep(3) if __name__ == '__main__': p1 = Process(target=get_input, args=()) p1.start() this is clearly not working, since the sys.stdin objects are different for main process and p1. So I have tried this to solve it,
//myscript.py def get_input(temp): while True: text = temp.readline() print "hello " + text time.sleep(3) if __name__ == '__main__': p1 = Process(target=get_input, args=(sys.stdin,)) p1.start() but I come across with this error;
Process Process-1: Traceback (most recent call last): File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap self.run() File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run self._target(*self._args, **self._kwargs) File "in.py", line 12, in get_input text = temp.readline() ValueError: I/O operation on closed file So, I guess that main's stdin file closed and I can't read from it. At this conjunction, how can I pass main's stdin file to another process? If passing stdin is not possible, how can I use main's stdin from another process?
update: Okay, I need to clarify my question since people think using multiprocessing is not really necessary. consider myscript.py like this;
//myscript.py def get_input(): while True: text = sys.stdin.readline() print "hello " + text time.sleep(3) def do_more_things(): while True: #// some code here time.sleep(60*5) if __name__ == '__main__': p1 = Process(target=get_input, args=()) p1.start() do_more_things() so, I really need to run get_input() function parallelly with main function (or other sub processes). Sorry for the conflicts, I have a decent English, and I guess I couldn't be clear on this question. I would appreciate if you guys can tell me if i can use the main processes STDIN object in another process.
thanks in advance.
myscript.pycreate a subprocess? Why doesn't it simply read from sys.stdin? If it read fromsys.stdinthe shell script would work perfectly. Why create a subprocess?( python writer.py | python myscript.py ) & python do_more_things.py? I don't see why this isn't simply three separate Python programs. Two form a trivial pipeline, and the third is totally unrelated.