shaveax shaveax - 1 year ago 88
Python Question

how to delete 0 form from os.system in python?

I was wondering how can I delete the 0 from

in python, for example, in this variable I can delete it without any issues:

user_name = check_output('whoami').strip()
output = current-user

but the thing is that when I run this variable :

from subprocess import check_output

subtests = os.system('/home/' + user_name + '/tests/cfile --list-subtests')
output = subtests 1
subtests 2

and if I apply the same command structure from the first command like

subtests = check_output('/home/' + user_name + '/intel-graphics/intel-gpu-tools/tests/' + line + ' --list-subtests').strip()

it does not works, I get several python's errors, I was researching a lot, but so far I could not find a good fix for this.

Note: I'mm using python 2.7

Answer Source

When you call os.system, it starts a new process. That process' standard input and output streams are connected to your Python program ones.

I.e. when you call os.system whatever the child process outputs gets written to the terminal (or whereever your main program output goes). Just like this:

>>> result = os.system(".../cfile --list-subtests")
subtests 1
subtests 2
>>> result

The "subtests 1"/"subtests 2" lines above is just a text that had passed from the child process to the terminal. It had never been processed by Python or went to any variable. The returned value was just 0, which usually means the operation had completed successfully.

If you want to capture the output use the subprocess module, either check_output (exactly like you have used in your first example!) or generic Popen:

>>> process = subprocess.Popen([".../cfile", "--list-subtests"], stdout=subprocess.PIPE)
>>> process_out, process_err = process.communicate()
>>> process_out
'subtests 1\nsubtests 2\n'
>>> process.returncode