Code:
# cat mylinux.py
# This program is to interact with Linux
import os
v = os.system("cat /etc/redhat-release")
Output:
# python mylinux.py
Red Hat Enterprise Linux Server release 7.6 (Maipo)
In the above output, the command output is displayed regardless of the variable I defined to store the output.
How to store the shell command output to a variable using os.system method only?
CodePudding user response:
By using module subprocess
. It is included in Python's standard library and aims to be the substitute of os.system
. (Note that the parameter capture_output
of subprocess.run
was introduced in Python 3.7)
>>> import subprocess
>>> subprocess.run(['cat', '/etc/hostname'], capture_output=True)
CompletedProcess(args=['cat', '/etc/hostname'], returncode=0, stdout='example.com\n', stderr=b'')
>>> subprocess.run(['cat', '/etc/hostname'], capture_output=True).stdout.decode()
'example.com\n'
In your case, just:
import subprocess
v = subprocess.run(['cat', '/etc/redhat-release'], capture_output=True).stdout.decode()
Update: you can split the shell command easily with shlex.split
provided by the standard library.
>>> import shlex
>>> shlex.split('cat /etc/redhat-release')
['cat', '/etc/redhat-release']
>>> subprocess.run(shlex.split('cat /etc/hostname'), capture_output=True).stdout.decode()
'example.com\n'
Update 2: os.popen
mentioned by @Matthias
However, is is impossible for this function to separate stdout and stderr.
import os
v = os.popen('cat /etc/redhat-release').read()