如何用Python执行linux命令

By 刘志军, 2020-06-04, 分类: qa

python

方法1: 使用 subprocess.call

如果你在Linux中执行的命令是:

ls -l

那么你只要将命令按空格分隔,转换成列表,作为参数传给 subprocess.call 即可。

>>> import subprocess
>>> subprocess.call(["ls", "-l"])
total 72
lrwxrwxrwx   1 root root     7 Jul 19  2018 bin -> usr/bin
dr-xr-xr-x   5 root root  4096 Dec  1  2018 boot
drwxr-xr-x   3 root root  4096 Nov 10  2019 data
drwxr-xr-x  19 root root  2980 May 23 00:12 dev
drwxr-xr-x  89 root root  4096 Apr 16 21:43 etc
drwxr-xr-x   4 root root  4096 Dec 14 23:10 home
lrwxrwxrwx   1 root root     7 Jul 19  2018 lib -> usr/lib
lrwxrwxrwx   1 root root     9 Jul 19  2018 lib64 -> usr/lib64
drwx------   2 root root 16384 May 12  2016 lost+found
drwxr-xr-x   2 root root  4096 Apr 11  2018 media
drwxr-xr-x   2 root root  4096 Apr 11  2018 mnt
drwxr-xr-x   2 root root  4096 Apr 11  2018 opt
dr-xr-xr-x 113 root root     0 Feb  5 00:22 proc

方法2:使用 subprocess.run

subprocess.run 是 python3.5 引入的方法,如果你是使用python,那么推荐用此方法。

>>> import subprocess
>>> subprocess.call(["ls", "-l"])
total 72
lrwxrwxrwx   1 root root     7 Jul 19  2018 bin -> usr/bin
dr-xr-xr-x   5 root root  4096 Dec  1  2018 boot
drwxr-xr-x   3 root root  4096 Nov 10  2019 data
drwxr-xr-x  19 root root  2980 May 23 00:12 dev
drwxr-xr-x  89 root root  4096 Apr 16 21:43 etc
drwxr-xr-x   4 root root  4096 Dec 14 23:10 home
lrwxrwxrwx   1 root root     7 Jul 19  2018 lib -> usr/lib
lrwxrwxrwx   1 root root     9 Jul 19  2018 lib64 -> usr/lib64
drwx------   2 root root 16384 May 12  2016 lost+found
drwxr-xr-x   2 root root  4096 Apr 11  2018 media
drwxr-xr-x   2 root root  4096 Apr 11  2018 mnt
drwxr-xr-x   2 root root  4096 Apr 11  2018 opt
dr-xr-xr-x 113 root root     0 Feb  5 00:22 proc

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

python之禅

猜你喜欢

2018-09-27
关于Python包和模块的10个知识清单
2017-11-03
Python陷阱:为什么不能用可变对象作为默认参数的值
2020-06-07
求求你,别再手工造假数据了,fake了解一下
2020-06-14
python 获取当前时间
2020-06-14
python中如何将字符串转换为整数
2019-03-09
30个Python 小例子,帮你快速上手Python
2020-01-01
Python2.7: 2020年4月还会发布一个版本
2017-02-05
Python 表达式 i += x 与 i = i + x 等价吗?
2018-10-15
提升逼格的两个函数:setdefault 与 defaultdict
2017-10-24
自学Python编程怎么学才不那么孤独