Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using greater than operator with subprocess.call

What I am trying to do is pretty simple. I want to call the following command using python's subprocess module.

cat /path/to/file_A > file_B

The command simply works and copies the contents of file_A to file_B in current working directory. However when I try to call this command using the subprocess module in a script it errors out. Following is what I am doing:

import subprocess

subprocess.call(["cat", "/path/to/file_A", ">", "file_B"])

and I get the following error:

cat: /path/to/file_A: No such file or directory
cat: >: No such file or directory
cat: file_B: No such file or directory

what am I doing wrong ? How can I use the greater than operator with subprocess modules call command ?

like image 754
Amyth Avatar asked Jan 15 '14 11:01

Amyth


People also ask

Does subprocess call raise exception?

The Python subprocess call() function returns the executed code of the program. If there is no program output, the function will return the code that it executed successfully. It may also raise a CalledProcessError exception.

Should I use Popen or subprocess?

The main difference is that subprocess. run() executes a command and waits for it to finish, while with subprocess. Popen you can continue doing your stuff while the process finishes and then just repeatedly call Popen. communicate() yourself to pass and receive data to your process.

How do you pass command line arguments in subprocess?

You can pass a string to the command to be executed by subprocess. run method by using “input='string'” argument. As you can see, the code above passes “data. txt” as a string and not as a file object.

What is the difference between subprocess call and Popen?

Popen is more general than subprocess. call . Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.


1 Answers

> output redirection is a shell feature, but subprocess.call() with an args list and shell=False (the default) does not use a shell.

You'll have to use shell=True here:

subprocess.call("cat /path/to/file_A > file_B", shell=True)

or better still, use subprocess to redirect the output of a command to a file:

with open('file_B', 'w') as outfile:
    subprocess.call(["cat", "/path/to/file_A"], stdout=outfile)

If you are simply copying a file, use the shutil.copyfile() function to have Python copy the file across:

import shutil

shutil.copyfile('/path/to/file_A', 'file_B')
like image 167
Martijn Pieters Avatar answered Nov 10 '22 03:11

Martijn Pieters