使用sh库执行shell命令

python中执行shell命令

之前执行shell命令多是通过os.system(shell命令)的方式来执行,比较麻烦。

了解到sh是一个比subprocess好的库,能够执行shell命令

1.查看ip:

[root@iZj6cbstl2n6r280a27eppZ myblog]# ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.31.253.193 netmask 255.255.240.0 broadcast 172.31.255.255
ether 00:16:3e:01:72:ac txqueuelen 1000 (Ethernet)
RX packets 235322 bytes 231762359 (221.0 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 78402 bytes 15382388 (14.6 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

用sh完成:

In [13]: from sh import ifconfig

In [14]: print ifconfig("eth0")
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 172.31.253.193 netmask 255.255.240.0 broadcast 172.31.255.255
ether 00:16:3e:01:72:ac txqueuelen 1000 (Ethernet)
RX packets 236463 bytes 231849592 (221.1 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 79234 bytes 15505613 (14.7 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

2.查看/app目录下的文件:

In [24]: print sh.ls("/app")
git-2.14.1 myblog pyinit.py v2.14.1.tar.gz

In [27]: sh.ls("-l", "/app")
Out[27]:
drwxrwxr-x 26 root root 24576 9?. 12 20:52 git-2.14.1
drwxr-xr-x 6 root root 4096 9?. 13 21:53 myblog
-rw-r--r-- 1 root root 273 9?. 12 20:43 pyinit.py
-rw-r--r-- 1 root root 6983655 9?. 12 20:48 v2.14.1.tar.gz

查看/app下有多少个文件:

In [28]: sh.wc(sh.ls("-l", "/app"), "-l")
Out[28]: 5

3. 将/app下的文件存到列表里:

In [42]: list=sh.glob('/app/*')

In [43]: list
Out[43]: ['/app/git-2.14.1', '/app/v2.14.1.tar.gz', '/app/pyinit.py', '/app/myblog']

4.管道:

In [45]: print(sh.sort(sh.du(sh.glob('/app/*'),'-shc'),'-rn'))
397M ?.?
378M /app/git-2.14.1
13M /app/myblog
6.7M /app/v2.14.1.tar.gz
4.0K /app/pyinit.py

转载于:https://www.cnblogs.com/niansi/p/7541405.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值