user104323
user104323

Reputation: 55

Python - os.system is placing an unwanted (and unnecessary) newline and a 0 at the end of output

I don't know why it's doing this and when I try to trim it it spits out an error.

>>> print os.system('uptime')
21:05  up  9:40, 2 users, load averages: 0.69 0.76 0.82
0
>>> print os.system('uptime')[:-2]
21:07  up  9:42, 2 users, load averages: 0.75 0.74 0.80
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not subscriptable

Does anyone know how I can stop this from happening or how to remove it without an error? Thanks!

Upvotes: 5

Views: 4384

Answers (4)

johnsyweb
johnsyweb

Reputation: 141790

os.system() first executes the command in a subshell. That subshell prints the first line that you see.

On Unix, the return value is the exit status of the process. That is the 0 that you see in the interpreter. You could suppress this by assigning it to a variable:

>>> x = os.system('uptime')
14:12  up 21:45, 4 users, load averages: 1.13 0.93 0.82
>>> 

Alternatively, using subprocess.call():

>>> import subprocess
>>> status = subprocess.call('uptime')
14:19  up 21:52, 4 users, load averages: 1.12 0.93 0.86
>>> print status
0

Perhaps you'd rather capture both the output and the returned status in variables, so that you can manipulate these before displaying them (or not):

>>> pipe = subprocess.Popen(['uptime'], stdout=subprocess.PIPE, shell=True)
>>> 
>>> for line in pipe.stdout:
...     print line
... 
14:36  up 22:10, 4 users, load averages: 0.59 0.59 0.65

>>> status = pipe.wait()
>>> 
>>> print status
0

Upvotes: 3

Daan Lubbers
Daan Lubbers

Reputation: 143

You shouldn't have to print the output.

The actual command called by os.system prints to stdout and the function os.system() returns the return of the command as an integer.

So try

os.system('uptime')

Upvotes: 0

Cairnarvon
Cairnarvon

Reputation: 27762

os.system isn't doing any such thing; what is happening is that uptime itself is writing to stdout (real stdout, not Python's sys.stdout), and os.system is returning the return value of uptime, which is 0 (indicating it exited successfully).

If you want to access the string uptime prints to stdout within Python, you'll have to use some other way of calling it, like subprocess.Popen.

>>> import subprocess
>>> uptime = subprocess.Popen('uptime', stdout=subprocess.PIPE)
>>> output = uptime.stdout.read()
>>> output
' 04:20:09 up 12:13,  5 users,  load average: 0.99, 1.15, 1.25\n'

See the subprocess documentation for more details.

Upvotes: 6

Ali-Akber Saifee
Ali-Akber Saifee

Reputation: 4596

os.system does not return the contents of stdout. if you want to capture those use os.popen("uptime").read()

Upvotes: 2

Related Questions