原文出处: https://blog.xugaoxiang.com/python/python-module-6-sh-fire.html
软硬件环境
- ubuntu 18.04 64bit
- anaconda3 with python 3.7.1
- sh 1.12.14
- fire
sh
sh
是一个完美替代subprocess
的方案,它能帮助你方便的启动其它程序。
安装sh
pip install sh
sh
中封装了很多的shell
命令,但是官方宣称sh is not a collection of system commands implemented in Python.
In[2]: import sh
In[3]: sh.ifconfig('enp0s25')
Out[3]:
enp0s25: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.1.182 netmask 255.255.255.0 broadcast 192.168.1.255
inet6 fe80::9f51:6b1e:2a44:524c prefixlen 64 scopeid 0x20<link>
ether 50:7b:9d:d5:13:e6 txqueuelen 1000 (Ethernet)
RX packets 2107249 bytes 2099954336 (2.0 GB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 1343257 bytes 1630798979 (1.6 GB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
device interrupt 20 memory 0xe1300000-e1320000
再看看grep
的一个示例,比如我的系统中跑了多个ffmpeg
的进程,然后需要找到其中的某一个,获取到进程的pid
xugaoxiang@ubuntu:~$ ps ax | grep ffmpeg
15133 pts/1 S+ 1:54 ffmpeg -i rtsp://admin:[email protected]:554 -c:a copy -c:v copy -y -f flv rtmp://192.168.1.97:2935/live/192.168.2.118:554/index
19252 pts/1 S+ 0:00 ffmpeg -i rtsp://admin:[email protected]:554 -c:a copy -c:v copy -y -f flv rtmp://192.168.1.97:2935/live/192.168.2.119:554/index
19491 pts/6 S+ 0:00 grep --color=auto ffmpeg
import sh
def get_pid(expression):
"""
:param expression: 字符串辨识符,如这里的ip地址 192.168.2.118:554
:return: 进程的pid
"""
p = sh.grep(sh.ps("ax"), expression)
return p.stdout.decode('utf8').lstrip().split(' ')[0]
fire
fire
与python实用模块推荐(1)_click_pathlib中介绍过click
模块功能类似,但是fire
使用起来更加的方便简单(基本上不用写代码及文档注释),功能更加强大。
安装fire
pip install fire
import fire
def hello(name):
return 'Hello {name}!'.format(name=name)
if __name__ == '__main__':
fire.Fire()
如上面的示例所示,只需要fire.Fire()
就完成了命令行参数的构建,运行方法是
python example.py hello world
其中example.py
是文件名,hello
是方法名,world
是传递给hello
方法的参数;另外你可以明确的给方法构建,如下调用fire.Fire(hello)
,那么运行的时候就可以省略掉hello
方法了,python example.py world
fire.Fire()
的参数可以是方法,对象,类,字典,来看个字典的例子
import fire
def add(x, y):
return x + y
def multiply(x, y):
return x * y
if __name__ == '__main__':
fire.Fire({
'add': add,
'multiply': multiply,
})
运行
$ python example.py add 1 2
3
$ python example.py multiply 3 4
12
如果参数是类的话,跟字典传递的功能类似,即类的每个方法都可以接受命令行参数。