假设我像这样调用脚本;
$ python writer.py | python myscript.py
这里是代码:
// 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()
显然这不起作用,因为主进程和p1进程的sys.stdin对象是不同的。所以我尝试了以下方法来解决这个问题:
//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()
但我遇到了这个错误;
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
所以,我猜测main的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()
所以,我真的需要将 get_input() 函数与主函数(或其他子进程)并行运行。
抱歉有一些矛盾,我的英语还不错,但是我想我在这个问题上没有表述清楚。如果您能告诉我是否可以在另一个进程中使用主进程的 STDIN 对象,我会非常感激。
提前感谢。
( python writer.py | python myscript.py ) & python do_more_things.py
吗?我不明白为什么这不只是三个独立的 Python 程序。前两个构成一个微不足道的管道,第三个则完全无关。 - S.Lott