Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 526
user104323 Avatar asked Dec 20 '22 09:12

user104323


1 Answers

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.

like image 178
Cairnarvon Avatar answered Apr 27 '23 01:04

Cairnarvon