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.
You have to use
subprocess.Popen
if you want to send data to/from stdin/stdout of your subprocesses. And you have toPopen
a subprocess for each of the executables, i.e. in your example, one forecho
and one forxargs
.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.