-1

I run the following:

from subprocess import call
call(["uptime"])

I get:

19:36:49 up 4 days, 5:58, 14 users, load average: 0.46, 0.32, 0.40

Question: I want to split this string into words (each separated by blankspace) so that I can check for a certain amount of load. How do I do this?

Many thanks!

user3236841
  • 1,088
  • 1
  • 15
  • 39
  • possible duplicate of [Store output of subprocess.Popen call in a string](http://stackoverflow.com/questions/2502833/store-output-of-subprocess-popen-call-in-a-string) – Nir Alfasi May 09 '15 at 01:01

2 Answers2

1
from datetime import timedelta

with open('/proc/uptime', 'r') as f:
    uptime_seconds = float(f.readline().split()[0])
    uptime_string = str(timedelta(seconds = uptime_seconds))

print(uptime_string)
Siddarth
  • 1,000
  • 1
  • 10
  • 17
  • I get the following: words = string.split() Traceback (most recent call last): File "", line 1, in AttributeError: 'int' object has no attribute 'split' – user3236841 May 09 '15 at 01:03
  • Works, but I am interested in the three load averages from the uptime command, not in the uptime. – user3236841 May 09 '15 at 01:05
1

You're looking for subprocess.check_output.

Like so (in the interpreter):

>>> import subprocess
>>> output = subprocess.check_output("uptime", shell=False)
>>> print output.split()
['18:06:24', 'up', '16', 'days,', '22:40,', '8', 'users,', 'load', 'average:', '0.30,', '0.45,', '0.59']

For more, see https://docs.python.org/2/library/subprocess.html#subprocess.check_output

hlmtre
  • 28
  • 4