python - 在 Python 中逐行写入管道的正确方法

标签 python shell unix subprocess pipe

如何从 Python 写入标准输出并将其同时(通过 Unix 管道)提供给另一个程序?例如,如果你有

# write file line by line
with open("myfile") as f:
  for line in f:
    print line.strip()

但是您希望逐行转到另一个程序,例如| wc -l 以便它输出 myfile 中的行。那怎么办?谢谢。

最佳答案

如果你想在外部将 python 传输到 wc,这很简单,而且可以正常工作:

python myscript.py | wc -l

如果你想 tee 它以便它的输出既被打印又被管道传输到 wc,试试 man tee 或者,更好的是,你的 shell 内置的花式重定向功能.

如果您希望从脚本中运行 wc -l,并将您的输出发送到 stdout 和它,您也可以这样做。

首先,使用subprocess.Popen开始 wc -l:

wc = subprocess.Popen(['wc', '-l'], stdin=subprocess.PIPE)

现在,你可以这样做:

# write file line by line
with open("myfile") as f:
  for line in f:
    stripped = line.strip()
    wc.stdin.write(stripped + '\n')

这将使 wc 的输出与您的脚本输出到相同的位置。如果这不是您想要的,您也可以将其 stdout 设为 PIPE。在这种情况下,您想使用 communicate而不是尝试手动正确获取所有繁琐的细节。

关于python - 在 Python 中逐行写入管道的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14409483/

相关文章:

python - 通过追加 pandas 中不同数据帧的列来创建列

python - Python 中的 NameError - 不确定是类还是函数导致了错误

linux - 使用&&和||时如何执行exit命令?

shell - `[ -f ... ]` 是什么意思?

python - 值错误 : unconverted data remains on Pandas DataFrame

python - NGINX Unit + Flask = 在可用的应用程序模块中找不到

mysql - 使用 shell 脚本执行多个 MySQL 命令的更好方法

python - 将一个正在运行的程序的输出流通过管道传输到另一正在运行的程序的输入流

unix - 命令在 emacs shell 中运行的速度会慢很多吗?我怎样才能防止这种情况但仍然使用它?

c++ - gcc 显示来自系统库的错误。 -isystem 不工作