subprocess
模块是官方推荐使用的一个系统函数调用模块,而getoutput
方法则是模仿真实的Shell,下面看一下案例
代码(Windows)
# -*- coding: UTF-8 -*-
import subprocess
cmd = 'ipconfig'
print(subprocess.getoutput(cmd))
执行结果(windows)
代码(Linux)
# -*- coding: UTF-8 -*-
import subprocess
cmd = 'ip a | grep MU'
print(subprocess.getoutput(cmd))
执行结果(linux)
root@l:~# cat sub.py
# -*- coding: UTF-8 -*-
import subprocess
cmd = 'ip a | grep MU'
print(subprocess.getoutput(cmd))
root@l:~# python3 sub.py
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
45: veth9f9546c@if44: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
root@l:~# ip a | grep MU
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
45: veth9f9546c@if44: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
root@l:~#