使 Python 脚本与 xargs 一起工作 [英] Making Python scripts work with xargs
问题描述
使我的 Python 脚本与xargs"配合良好的过程是什么?例如,我希望以下命令可以处理文本文件的每一行,并执行任意命令:
What would be the process of making my Python scripts work well with 'xargs'? For instance, I would like the following command to work through each line of text file, and execute an arbitrary command:
cat servers.txt | ./hardware.py -m
基本上希望每一行都被传递给 hardware.py 脚本.
Essentially would like each line to be passed to the hardware.py script.
推荐答案
要使您的命令与 xargs
一起使用,您只需要它们接受参数即可.Python 中的参数位于 sys.argv
列表中.通过这种方式,您可以执行以下操作:
To make your commands work with xargs
you simply need them to accept arguments. Arguments in Python are in the sys.argv
list. In this way you can execute somthing like:
find . -type f -name '*.txt' -print0 | xargs -0 ./myscript.py
可能等价于
./myscript.py ./foo.txt ./biz/foobar.txt ./baz/yougettheidea.txt
为了使您的命令与标准输入一起工作,您还可以使用 sys
模块,这次使用 sys.stdin
,您可以将其视为文件.这更像是你给出的例子:
To make your commands work with standard input, you can also use the sys
module, this time with sys.stdin
, which you can treat as a file. This is more like the example you gave:
./myscript.py < somefile.txt
这篇关于使 Python 脚本与 xargs 一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!