Linux 如何通过python中的shell管道接收参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6106437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:14:04  来源:igfitidea点击:

How to receive arguments via shell pipe in python?

pythonlinuxshellpipe

提问by Woltan

I would like to do something like this:

我想做这样的事情:

find -name "foo*" | python main.py

and access all the files that were found by the find program. How do I access that in Python?

并访问 find 程序找到的所有文件。我如何在 Python 中访问它?

采纳答案by Andreas Jung

import sys
for line in sys.stdin:
    print line

回答by David Claridge

Use sys.stdin.read() or raw_input()

使用 sys.stdin.read() 或 raw_input()

A pipeline just changes the stdin file descriptor to point to the pipeline that the command on the left is writing to.

管道只是将 stdin 文件描述符更改为指向左侧命令正在写入的管道。

回答by manojlds

I think you can do:

我认为你可以这样做:

import sys
print sys.stdin.readlines() #or what you want

回答by Michael Kent

I believe fileinputmay be what you want.

我相信fileinput可能是你想要的。

回答by user2343996

I Like using $(...) for command-line arguments that are dependent on some other program. I think this would work for your program python main.py $(find -name "foo*"). Found here

我喜欢将 $(...) 用于依赖于其他程序的命令行参数。我认为这对你的程序有用python main.py $(find -name "foo*")。在这里找到