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, '\xe5\xb9\xb3\xe5\x9d\x87\xe6\x97\xb6\xe9\x97\xb4: 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']

转载于:https://www.cnblogs.com/mengmengzhang/p/9667247.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Pythonsubprocess库是用于调用Linux shell命令并返回状态和结果的库。它取代了Python2.4以上版本的commands模块,可以在Python中创建并运行一个外部程序的子进程。subprocess库中定义了多个创建子进程的函数,可以根据需要选择适合的函数来创建子进程。此外,subprocess还提供了管理标准流和管道的工具,以实现进程间的文本通信。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python subprocess库六个实例详解](https://blog.csdn.net/yaxuan88521/article/details/127898313)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [Python subprocess库的使用详解](https://download.csdn.net/download/weixin_38727199/13778453)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Python subprocess模块学习总结](https://blog.csdn.net/weixin_34414196/article/details/91916639)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值