简体   繁体   中英

how to split output of system call in python into list of words?

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!

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM