Python - Call an External Command

Python - Call an External Command

python, python external command, shell command, STDIN, STDOUT

Learning how to run an external command from inside python is fairly straightforward. Python supports several methods for calling an external command. Determining which method to use depends on the use case, view our examples below of calling an external command.


The recommended way to execute an external command in Python is by using the subprocess module. The example below uses the call() method to invoke a command.['ls', '-l'])
# prints
total 20
-rwxr--r-- 1 xxxxxxx xxxxxxx   36 Feb 26 12:14 test.txt

Redirecting STDOUT to a File

To redirect the output from the command to a file, first open the file and then use the stdout parameter. View the example below.

with open('test.txt', 'w') as f:['date'], stdout=f)
# cat test.txt
Tue Feb 26 09:27:12 UTC 2018

Passing Input from STDIN to Command

To pass input into STDIN of the child process, first use call() to open the file. Then pass the handle using the stdin parameter.

with open('test.txt', 'r') as f:['cat'], stdin=f)
# prints the text in test.txt
hello world
this is the second line.


Executing a Shell Command

You can also pass the shell parameter into the call() method, shell=True. This allows the command line to be parsed by the shell. View the shell parameter being passed below.'cat test.txt', shell=True)
# prints
hello world
this is the second line.

Exiting Code from a Command

You can also exit code from a command. The value is returned from the function call(). 

print 'returncode: ',['cat', 'test.txt'])
# prints
cat: test.txt: No such file or directory
returncode:  1

Back to The Programmer Blog