Python:使用来自另一个命令的输入 [英] Python: Use input from another command
问题描述
我想知道如何管理来自python脚本的另一个命令的输入。
I am wondering how can I manage input from another command from a python script.
示例:
$ cat myfile.txt | my_python_script.py
$ cat myfile.txt | my_python_script.py
我的脚本如何管理cat命令的输入流?如何从这个管道命令获取输入?
How can my script manage the input stream from the cat command ? How Can I get an input from this piped commands ?
...非常感谢。
推荐答案
使用 fileinput
模块来实现这一功能是一种简单而相当灵活的方法。
An easy and quite versatile way to accomplish this is to use the fileinput
module.
import fileinput
for line in fileinput.input()
# do things with line
这样,你可以在管道中使用脚本(正如你现在所需要的),或者将一个或多个文件作为参数提供给脚本 my_python_script.py input.txt input2.txt
)。
This way you can both use the script in a pipeline (as you need to right now) or give one or more files to the script as a parameter (think my_python_script.py input.txt input2.txt
).
这篇关于Python:使用来自另一个命令的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!