![](/img/trans.png)
[英]How to send stdout of one Python program over UDP to stdin of another using BASH?
[英]Linux : stdout of one program to stdin of another program
我从另一个程序中的一个程序中读取Reading stdout,但没有找到我要的答案
我是Linux的新手,我在Python中使用argparse模块通过Mac上的终端通过程序运行参数
我有program_1.py,它通过sys.stdin输入文件并将数据输出到sys.stdout
我正在尝试让program_2.py接收从program_1.py输出到sys.stdout的数据,并将其作为sys.stdin接收
我尝试了以下方法:
Mu$ python program-1.py <sample.txt> program-2.py
为了简单起见,假设“ sample.txt”只有字符串“ 1.6180339887”
program_2.py如何从先前程序的sys.stdout读取为sys.stdin?
在这个简单的示例中,我只是想让program_2.py将syslog.stdout输出为“ 1.6180339887”,这样我才能知道它是如何工作的。
有人告诉我使用| 管道的字符,但我无法使其正常工作
使用管道是正确的:
python program-1.py sample.txt | python program-2.py
这是一个完整的示例:
$ cat sample.txt
hello
$ cat program-1.py
import sys
print open(sys.argv[1]).read()
$ cat program-2.py
import sys
print("program-2.py on stdin got: " + sys.stdin.read())
$ python program-1.py sample.txt
hello
$ python program-1.py sample.txt | python program-2.py
program-2.py on stdin got: hello
(PS:您本可以在问题中包含一个完整的测试用例。这样,人们可以说您做错了什么,而不是自己编写)
program-1.py:
import sys
if len(sys.argv) == 2:
with open(sys.argv[1], 'r') as f:
sys.stdout.write(f.read())
program-2.py:
import sys
ret = sys.stdin.readline()
print ret
为sample.txt
1.6180339887
在您的外壳中:
Mu$ python p1.py txt | python p2.py
输出:
1.6180339887
此处提供更多信息: http : //en.wikipedia.org/wiki/Pipeline_(Unix)和此处http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.