Skip to content Skip to sidebar Skip to footer

How To Hide Or Delete The 0 When Call To `os.system` In Python?

How can I hide / eliminate the output 0 and the new line that the os.system command in Python produces when you call it? For example: import os os.system('whoami') Output: userX 0

Solution 1:

What about this?

from subprocess import check_output
user_name = check_output('whoami').strip()
print user_name
#out: userX

Solution 2:

Asuming your using the python console

>>> import os
>>> os.system('whoami')
userX
0

this 0 actually is the return value of os.system('whoami') and is only shown on the console. With scripts you wouldn't have this output. So if you assign the value somehow, it would technically be hidden

>>> import os
>>> ret = os.system('whoami')
userX

Solution 3:

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'])

Post a Comment for "How To Hide Or Delete The 0 When Call To `os.system` In Python?"