python - Linux : stdout of one program to stdin of another program

标签 python linux terminal argparse pipeline

我 checkout Reading stdout from one program in another program却没有找到我要找的答案

我是 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 将“1.6180339887”输出到 sys.stdout,这样我就可以看到它是如何工作的。

有人告诉我使用 |管道的字符,但我无法使其正常工作

最佳答案

使用管道是正确的:

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:你可以在你的问题中包含一个完整的测试用例。这样,人们可以说你做错了什么,而不是自己写)

关于python - Linux : stdout of one program to stdin of another program,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26642265/

相关文章:

Java执行debian终端命令 "|"

visual-studio-code - 如何将我的 VS Code 终端更改为 cmd.exe 而不是 powershell?

python - python的pip支持http认证吗?

python - 如何使用 getattr 从模型中获取外键值

c - 哪些用户可以使用 setpgid() 函数?

shell - 箭头键在 shell 中不起作用

python - 我们有一个相当大的 django 站点,运行性能很差,我们需要帮助查找原因

python - python从elasticsearch结果创建数据框

linux - Bash 脚本从文本文件复制单词并在终端上运行

linux - Perl 系统中的嵌套引号()