Ruan Bekker's Blog

From a Curious mind to Posts on Github

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:

1
2
3
4
5
6
7
8
9
>>> import commands
>>> commands.getstatusoutput('echo foo')
(0, 'foo')

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

Command Output Only:

Only getting the Shell Output:

1
2
3
>>> import commands
>>> commands.getoutput('echo foo')
'foo'

Basic Script

Test file with a one line of data:

1
2
$ cat file.txt
test-string

Our very basic python script:

1
2
3
4
5
6
7
import commands

status = None
output = None

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

Running the script:

1
2
$ python script.py
Status: 0, Output: test-string