一、了解subprocess
- subeprocess模块是python自带的模块,无需安装,主要用来取代一些就的模块或方法,如os.system、os.spawn*、os.popen、commands.*等。
- 因此执行外部命令优先使用subprocess模块
1、subprocess.run()方法
subprocess.run()方法是官方推荐的方法,几乎所有的工作都可以用它来完成。
如下是函数源码:
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, ced=None, timeout=None, check=False, enccoding=None, error=None)
该函数返回一个CompletedProcess类(有属性传入参数及返回值)的实例,该函数的参数有很多,只需要记住常用的即可
1、args : 代表需要在操作系统中执行的命令,可以是字符串形式(要求shell=True),也可以是list列表类型
2、* :代表可变参数,一般是列表或者字典类型
3、stdin、std本文来源gaodai#ma#com搞@代~码^网+out、stderr :指定了可执行程序的标准输入、标准输出、标准错误文件句柄
4、shell :代表着程序是否需要在shell上执行,当想使用shell的特性时,设置shell=True,这样就可以使用shell指令的管道、文件名称通配符、环境变量等,不过python也提供了很多类似shell的模块,如glob、fnmatch、os.walk()、os.path.expandvars()、os.path.expanduser()和shutil。
5、check :如果check设置为True,就检查命令的返回值,当返回值为0时,将抛出AclledProcessError的异常
6、timeout :设置超时时间,如果超时则kill掉子进程
1.使用字符串方式执行shell命令
[root@localhost python]# vim 1.py #!/bin/env python3 import subprocess b=subprocess.run("ls -l /ltp | head -2", shell=True) # 执行run方法,并将返回值赋值给b # total 184980 # -rw-r--r--. 1 root root 10865 May 8 16:21 123.txt print(b) # 执行该run函数后返回的CompletedProcess类 # CompletedProcess(args='ls -l /ltp | head -2', returncode=0) print(b.args) # 打印出CompletedProcess类的agrs属性值,就是执行的shell命令 # ls -l /ltp | head -2 print(b.returncode) # 打印命令执行的状态码 # 0
结果展示
[root@localhost python]# ./1.py
total 184980
-rw-r–r–. 1 root root 10865 May 8 16:21 123.txtCompletedProcess(args=’ls -l /ltp | head -2′, returncode=0)2
ls -l /ltp | head -2
0
2.使用列表方式执行
个人感觉方法二不好用,尤其是想要使用管道符号是,很难用
#!/bin/env python3 import subprocess b = subprocess.run(["ls", "-l", "/ltp"]) print(b) print(b.args) print(b.returncode)
执行结果
[root@localhost python]# ./2.py
total 10865
-rw-r–r–. 1 root root 10865 May 8 16:21 123.txt
CompletedProcess(args=[‘ls’, ‘-l’, ‘/ltp’], returncode=0)
[‘ls’, ‘-l’, ‘/ltp’]
0
3.捕获脚本输出
- 如果需要采集命令执行的结果,可以传入参数stdout=subprocess.PIPE
[root@localhost python]# cat 3.py #!/bin/env python3 import subprocess # 传入stdout=subprocess.PIPE参数即可 b=subprocess.run("ls -l /ltp | head -2", shell=True, stdout=subprocess.PIPE) print(b.stdout)
结果显示
[root@localhost python]# ./1.py
b’total 184980\n-rw-r–r–. 1 root root 10865 May 8 16:21 123.txt\n’