perhaps you should have a look on subprocess.run
, there is a parameter in the function called capture output
, in the docs is described as follows:
If capture_output is true, stdout and stderr will be captured. When used, the internal Popen object is automatically created with stdout=PIPE and stderr=PIPE. The stdout and stderr arguments may not be supplied at the same time as capture_output. If you wish to capture and combine both streams into one, use stdout=PIPE and stderr=STDOUT instead of capture_output.
in the docs there is an example that shows how to get output from commands:
>>> subprocess.run(["ls", "-l", "/dev/null"], capture_output=True)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n',stderr=b'')
if you just want to get the current user, i would suggest os.getlogin
:
>>> import os
>>> if os.getlogin() != 'root':
... print("please run as root!")
please run as root!
NOTE: I would also suggest to not use shell=True
in the arguments, provides lots of security issues.