使用xargs(或者其他?)来顺序执行python脚本

时间:2017-02-13 12:18:58

标签: python xargs

这个问题几乎与this question重复,但差不多,而且没有一个答案符合我的目标。

我想要执行以下操作:拥有一个文件名列表,按顺序执行一个python脚本(!)和每个文件名。现在,我知道我可以轻松地解析我的python脚本中的文件名列表并执行每行上的任何函数,但这里的想法是我想将该批处理执行灵活性移到shell上,并保持我的python脚本不变。 / p>

所以我的参数文件看起来像这样:

$ cat arglist
1                  # <- separated by newlines
2
3
4

python脚本:

import sys
print("args received:",sys.argv)

我试过了:

$ cat arglist | xargs python ./pyxargs.py -a -b -c
args received: ['./pyxargs.py', '-a', '-b', '-c', '1', '2', '3', '4']

但我想要实现的是以下

args received: ['./pyxargs.py', '-a', '-b', '-c', '1']
args received: ['./pyxargs.py', '-a', '-b', '-c', '2']
args received: ['./pyxargs.py', '-a', '-b', '-c', '3']
args received: ['./pyxargs.py', '-a', '-b', '-c', '4']

我猜xargs的工作方式让我很困惑。或者它只是错误的工具,总是组合参数并执行单个执行,而不是单独的执行?如果是,xargs的适当替代方案是什么?

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

尝试使用-I

< arglist xargs -I file python ./pyxargs.py -a -b -c file

请注意,如果您的任何文件名包含换行符,则会失败,但这是尝试在文本文件中记录文件名时所固有的,因此这可能不会成为问题。