【问题标题】:Linux : stdout of one program to stdin of another programLinux:一个程序的标准输出到另一个程序的标准输入
【发布时间】:2014-10-29 23:12:05
【问题描述】:

我查看了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.stdin,如何从前一个程序的 sys.stdout 中读取?

在这个简单的示例中,我只是想让 program_2.py 将“1.6180339887”输出到 sys.stdout,这样我就可以看到它是如何工作的。

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

【问题讨论】:

  • 为了避免每次都添加python前缀,您可以在最顶部添加#!/usr/bin/env python line (shebang)并为脚本设置可执行权限:chmod +x program_1.py。之后,您可以将脚本运行为./program_1.py

标签: python linux terminal argparse pipeline


【解决方案1】:

使用管道是正确的:

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

【讨论】:

  • @O.rka 我不知道,你没有发布任何代码或错误消息
  • 我的错误信息是:错误:无法识别的参数:sample.txt
  • @O.rka,如果 &lt;sample.txt 被 shell 正确处理,它根本不会传递给你正在调用的程序,所以它不可能是无法识别的争论。如果您确切地向我们展示了您是如何产生问题的,并且在足够的上下文中我们可以自己重现它......
  • @CharlesDuffy:如果使用了答案中的错误命令,则会发生错误。 OP的问题明确指出program_1.py“通过sys.stdin输入文件”,即应该使用&lt;sample.txt(无错误),但答案中的命令使用program-1.py sample.txt(因此出现错误)。
  • @O.rka:你想要类似的东西:&lt;sample.txt python program-1.py | python program-2.py
【解决方案2】:

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

示例.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

【讨论】:

    猜你喜欢
    • 2017-02-03
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-26
    • 2023-04-02
    • 1970-01-01
    相关资源
    最近更新 更多