如何使用脚本调用xargs

how to call xargs using script

我是python的新手,还处于基础学习的水平。最近我尝试编写一个脚本来根据输入文本文件中提供的数字生成新文件夹。创建这些文件夹后,我想同时将一个文件复制到所有这些文件夹中。我可以输入

echo equil{1..x} | xargs -n 1 cp *.txt *

在终端中,它工作正常。这里 x 是我工作目录中的文件夹数。但我关心的是让它自动运行,即从脚本中调用它,这样用户就不需要每次都在终端中输入这一行。这就是我尝试这个的原因

sub2 = subprocess.call(['echo', 'equil{1..x}', '|', 'xargs', '-n', '1', 'cp', '*.txt *'])

任何人都可以指导我并告诉我错误。实际上我没有收到任何错误,而是打印了这个

equil{1..x} | xargs -n 1 cp *.txt *

执行脚本的其余部分后在终端中。

我认为您不能像这样对管道使用 subprocess.call()。有关如何使用管道的食谱,请参阅

https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline

即您将在两个进程中使用 subprocess.communicate()。

如果要发送子进程的数据 to/from stdin/stdout,则必须使用 subprocess.Popen。而且您必须 Popen 每个可执行文件的子进程,即在您的示例中,一个用于 echo 和一个用于 xargs.

文档中有一个示例:https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline

这里还有一个:Call a shell command containing a 'pipe' from Python and capture STDOUT

但是,不用运行 echo 来产生一些行,你可以直接在python 中将它们写入进程stdin