简体   繁体   English

如何将python中的系统调用的输出分成单词列表?

[英]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 19:36:49最多4天,5:58,14个用户,平均负载: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 . 您正在寻找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 有关更多信息,请参见https://docs.python.org/2/library/subprocess.html#subprocess.check_output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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