有没有办法将'stdin'作为参数传递给python中的另一个进程?

Muh*_*Can 16 python stdin multiprocessing

我正在尝试创建一个使用python的多处理模块的脚本.脚本(让我们称之为myscript.py)将从另一个带有管道的脚本获取输入.

假设我像这样调用脚本;

$ python writer.py | python myscript.py 
Run Code Online (Sandbox Code Playgroud)

这是代码;

// 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()
Run Code Online (Sandbox Code Playgroud)

这显然不起作用,因为sys.stdin对象对于主进程和p1是不同的.所以我试过这个解决它,

//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()
Run Code Online (Sandbox Code Playgroud)

但我遇到了这个错误;

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
Run Code Online (Sandbox Code Playgroud)

所以,我猜主要的stdin文件关闭了,我无法读取它.在这个结合处,我如何将main的stdin文件传递给另一个进程?如果无法传递stdin,我如何从另一个进程使用main的stdin?

更新: 好的,我需要澄清我的问题,因为人们认为使用多处理并不是真的有必要.myscript.py像这样考虑;

//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()
Run Code Online (Sandbox Code Playgroud)

所以,我真的需要与main函数(或其他子进程)并行运行get_input()函数.对不起冲突,我有一个体面的英语,我想我不能清楚这个问题.如果你们能告诉我是否可以在另一个进程中使用主进程STDIN对象,我将不胜感激.

提前致谢.

jfs*_*jfs 11

最简单的事情是交换get_input(),do_more_things()即读取sys.stdin父进程:

def get_input(stdin):
    for line in iter(stdin.readline, ''):
        print("hello", line, end='')
    stdin.close()

if __name__ == '__main__':
    p1 = mp.Process(target=do_more_things)
    p1.start()
    get_input(sys.stdin)
Run Code Online (Sandbox Code Playgroud)

接下来最好的事情是使用a Thread()而不是Process()for get_input():

if __name__ == '__main__':
    t = Thread(target=get_input, args=(sys.stdin,))
    t.start()
    do_more_things()
Run Code Online (Sandbox Code Playgroud)

如果以上情况没有帮助,您可以尝试os.dup():

newstdin = os.fdopen(os.dup(sys.stdin.fileno()))
try: 
   p = Process(target=get_input, args=(newstdin,))
   p.start()    
finally:
   newstdin.close() # close in the parent
do_more_things()
Run Code Online (Sandbox Code Playgroud)