什么是 sh
sh 是一个成熟的 subprocess 替代品,适用于 Python2 - 3,PyPy 和 PyPy3,它允许你以函数的方式调用任何 Shell 程序。就像这样:
1 2
| from sh import ifconfig print(ifconfig("wlan"))
|
输出为:
1 2 3 4 5 6 7 8
| wlan0 Link encap:Ethernet HWaddr 00:00:00:00:00:00 inet addr:192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0 inet6 addr: ffff::ffff:ffff:ffff:fff/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:0 errors:0 dropped:0 overruns:0 frame:0 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:0 (0 GB) TX bytes:0 (0 GB)
|
注意了,这可不是 Python 的功能,这些都是通过解析$PATH变量运行的你的系统上的二进制命令,就和 Bash 一样,然后转换为 Python 中的函数。这样,系统中的所有程序都可以轻松的用 Python 调用了。