python-3.x - 如何获取特定的字符串?

标签 python-3.x linux telegram-bot

def get_system_info():
      command = "free -h"
      return subprocess.check_output(command, shell=True).strip()
@bot.message_handler(commands=['si'])
def send_echo(message):
    bot.send_message(message.chat.id, get_system_info())

结果:

              total        used        free      shared  buff/cache   available
Mem:            62G         49G        5.3G         69M        7.5G         12G
Swap:          1.0G        5.8M        1.0G

我需要的结果:

Memory,
total: 62G
used: 49G
free: 5.3G
shared: 69M
buff/cache: 7.5G
available: 12G

我尝试通过分割线来做到这一点,但没有成功

最佳答案

您可以像这样继续:

# decode used to convert bytes into string, then split it around whitespaces/newlines
output = get_system_info().decode('utf-8').split()
d = {}
for i in range(0, 6):
    d[text[i]] = text[i + 7]

通过此,您可以捕获从totalavailable的键值对。我的机器的值:

>>> d
{'total': '15G', 'used': '6.9G', 'free': '486M', 'shared': '842M', 'buff/cache': '8.2G', 'available': '7.6G'}

我相信从现在开始您可以以任何您需要的格式打印这本词典。

关于python-3.x - 如何获取特定的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59744650/

相关文章:

linux - 在 linux 中使用 verbose 启动 tomcat

post - Golang 和 Telegram API 的 400 错误请求

python - 无法接收用户的更新消息

python - 使用python使用复制方法将json str插入postgresql时如何修复 "invalid input syntax for type json"

python - 与 0 比较的异常

linux - 如何在不使用日期的情况下更改本地时间

qt - 将 Qt 中的 setWebhook 用于 Telegram 机器人

python - 具有多个分隔符的拆分列表

python - 选择除 BeautifulSoup 中具有某些类的所有 div

ios - 如何设置 Linux BlueZ 5 连接参数以实现 Apple iOS 兼容性