Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return value of x = os.system(..) [duplicate]

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 ? (:

like image 319
Ramon Avatar asked Sep 23 '14 22:09

Ramon


People also ask

What is the return value of OS system?

os. system only returns the error value.

Does OS system return anything python?

os. system() you can execute a system command, but it does not return the output to Python. This will run a command on your system. On Linux and Mac the command pwd returns the current directory, but any command will do.

What is OS Popen in Python?

Description. Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'. The bufsize argument has the same meaning as in open() function.


1 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']) 
like image 184
Martijn Pieters Avatar answered Sep 19 '22 23:09

Martijn Pieters