在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']
