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

时间:2021-05-24 21:37:13

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 up 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!

2 个解决方案

#1


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

#2


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)

#1


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

#2


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)