When I type os.system("whoami")
in Python, as root, it returns root
, but when I try to assign it to a variable x = os.system("whoami")
it set's the value of x to 0. Why ? (:
2 Answers
os.system()
returns the (encoded) process exit value. 0
means success:
On Unix, the return value is the exit status of the process encoded in the format specified for
wait()
. Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.
The output you see is written to stdout
, so your console or terminal, and not returned to the Python caller.
If you wanted to capture stdout
, use subprocess.check_output()
instead:
x = subprocess.check_output(['whoami'])
-
I tried several ways to use subprocess but I always get
[Errno 9] Bad file descriptor
... what's wrong? .-. Oct 21, 2019 at 10:12 -
1@FabioMagarelli that’s impossible to say, without a minimal reproducible example. This is probably not something I can help with in comments, consider posting a question if you do have a good reproducible case.– Martijn Pieters ♦Oct 21, 2019 at 10:32
os.system('command')
returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.
Refer my answer for more detail in What is the return value of os.system() in Python?