欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python实用模块(十一)sh

实用模块 迷途小书童 4年前 (2019-12-03) 3190次浏览 0个评论

软硬件环境

  • ubuntu 18.04 64bit
  • anaconda3 with python 3.7.1
  • sh 1.12.14

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:rm123456@192.168.2.118: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:rm123456@192.168.2.119: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]

参考资料

喜欢 (0)

您必须 登录 才能发表评论!

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

请关闭 Adblock 等类似浏览器插件,然后刷新页面访问,感谢您的支持!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.