how to call xargs using script

2.2k views Asked by At

I am new to python and still at the level of basic learning. Recently I tried to write a script to generate new folders according to the number supplied in the input text file. After creating those folders I want to copy a file into all those folders at the same time. I can do it by typing

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

in the terminal, and it works fine. Here x is the number of folders I have in my working directory. But my concern is to make it automatic, i.e. to call it from the script, so that the user doesn't need to type this line every time in the terminal. That is why I tried this

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

Can anyone please guide me and show me the mistake. Actually I am not getting any error, rather it is printing this

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

in the terminal after executing the rest of the script.

2

There are 2 answers

2
fferri On BEST ANSWER

You have to use subprocess.Popen if you want to send data to/from stdin/stdout of your subprocesses. And you have to Popen a subprocess for each of the executables, i.e. in your example, one for echo and one for xargs.

There is an example in the docs: https://docs.python.org/2/library/subprocess.html#replacing-shell-pipeline

Another here: Call a shell command containing a 'pipe' from Python and capture STDOUT

However, instead of running echo to produce some lines, you can directly write them in python to the process stdin.

1
Leif Hedstrom On

I don't think you can use subprocess.call() like this with pipes. For recipes how to use pipes, see

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

I.e. you would use subprocess.communicate() over two processes.