Published on

Linux Shell Commands with the Python Commands Module


Using Python to Execute Shell Commands in Linux

Status Code and Output:

Getting the Status Code and the Output:

>>> import commands
>>> commands.getstatusoutput('echo foo')
(0, 'foo')

>>> status, output = commands.getstatusoutput('echo foo')
>>> print(status)
>>> print(output)

Command Output Only:

Only getting the Shell Output:

>>> import commands
>>> commands.getoutput('echo foo')

Basic Script

Test file with a one line of data:

$ cat file.txt 

Our very basic python script:

import commands

status = None
output = None

status, output = commands.getstatusoutput('cat file.txt')
print("Status: {}, Output: {}".format(status, output))

Running the script:

$ python 
Status: 0, Output: test-string

Thank You

Thanks for reading, feel free to check out my website, feel free to subscribe to my newsletter or follow me at @ruanbekker on Twitter.