- Published on
 
Linux Shell Commands with the Python Commands Module
- Authors
 
- Name
 - Ruan Bekker
 - @ruanbekker
 
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)
0
>>> print(output)
foo
Command Output Only:
Only getting the Shell Output:
>>> import commands
>>> commands.getoutput('echo foo')
'foo'
Basic Script
Test file with a one line of data:
$ cat file.txt 
test-string
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 script.py 
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.
- Linktree: https://go.ruan.dev/links
 - Patreon: https://go.ruan.dev/patreon