zoukankan      html  css  js  c++  java
  • python commands 和 subprocess

    在Python 2中,经常使用commands模块来执行shell的命令,尤其是常用getstatusoutput()函数。
    但是Python3中已经没有commands模块了,那么在Python 3中如果要调用一个命令,如何做呢?使用subprocess模块

    import commands
    import subprocess

    shell_commands = 'sar 1 3|grep "^平均时间:"'
    status,result = commands.getstatusoutput(shell_commands)
    print(status,result)
    -------->(0, 'xe5xb9xb3xe5x9dx87xe6x97xb6xe9x97xb4: all 3.42 0.00 1.49 0.00 0.00 95.10')
    print(type(commands.getstatusoutput(shell_commands)))
    --------><type 'tuple'>
    print(result.split()[2:]) # 取得cpu各个指标的值
    -------->['3.19', '0.00', '0.86', '0.09', '0.00', '95.87']

    result = subprocess.Popen(shell_command,shell=True,stdout=subprocess.PIPE)
    print(result)
    --------><subprocess.Popen object at 0x7fcd59974810>
    print(result.stdout.read())
    -------->平均时间: all 3.05 0.00 0.85 0.00 0.00 96.10
    print(type(result.stdout.read()))
    --------><type 'str'>
    print(result.stdout.read().split()[2:]) # 取得cpu各个指标的值
    -------->['9.54', '0.00', '1.39', '0.17', '0.00', '88.90']

  • 相关阅读:
    Flask-SQLAlchemy
    with 与 上下文管理器
    使用@property
    C++:如何把一个int转成4个字节?
    尝试理解Flask源码 之 搞懂WSGI协议
    qt setData()和data()
    我使用过的Linux命令之sftp
    linux下如何使用sftp命令
    Linux环境下安装JDK
    CentOS 6.5 配置IP地址的三种方法
  • 原文地址:https://www.cnblogs.com/mengmengzhang/p/9667247.html
Copyright © 2011-2022 走看看