一、Python执行外部命令
1、subprocess模块简介
subprocess 模块允许我们启动一个新进程,并连接到它们的输入/输出/错误管道,从而获取返回值。
这个模块用来创建和管理子进程。它提供了高层次的接口,用来替换os.system*()、 os.spawn*()、 os.popen*()、os,popen2.*()和commands.*等模块和函数。
subprocess提供了一个名为Popen的类启动和设置子进程的参数,由于这个类比较复杂, subprocess还提供了若干便利的函数,这些函数都是对Popen类的封装。
2、subprocess模块的遍历函数
linux安装ipython
pip3 install ipython
(1)call函数
call函数的定义如下:
subprocess.ca11(args, *, stdin=None, stdout=None, stderr=None, she11=False)
#运行由args参数提供的命令,等待命令执行结束并返回返回码。args参数由字符串形式提供且有多个命令参数时,需要提供shell=True参数
args:表示要执行的命令。必须是一个字符串,字符串参数列表。
stdin、stdout 和 stderr:子进程的标准输入、输出和错误。其值可以是 subprocess.PIPE、subprocess.DEVNULL、一个已经存在的文件描述符、已经打开的文件对象或者 None。subprocess.PIPE 表示为子进程创建新的管道。subprocess.DEVNULL 表示使用 os.devnull。默认使用的是 None,表示什么都不做。另外,stderr 可以合并到 stdout 里一起输出。
shell:如果该参数为 True,将通过操作系统的 shell 执行指定的命令。
示例代码:
[root@python ~]# ipython #启动ipython
Python 3.8.1 (default, Mar 9 2020, 12:35:12)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: import subprocess #调用函数
In [2]: subprocess.call(['ls','-l'])
drwxr-xr-x. 2 root root 6 10月 31 23:04 公共
drwxr-xr-x. 2 root root 6 10月 31 23:04 模板
drwxr-xr-x. 2 root root 6 10月 31 23:04 视频
drwxr-xr-x. 2 root root 4096 10月 31 22:40 图片
drwxr-xr-x. 2 root root 6 10月 31 23:04 文档
drwxr-xr-x. 2 root root 6 10月 31 23:04 下载
drwxr-xr-x. 2 root root 6 10月 31 23:04 音乐
drwxr-xr-x. 2 root root 6 10月 31 15:27 桌面
Out[2]: 0
In [3]: subprocess.call('exit 1',shell=True)
Out[3]: 1
(2)check_call函数
check_call函数的作用与call函数类似,区别在于异常情况下返回的形式不同。
对于call函数,工程师通过捕获call命令的返回值判断命令是否执行成功,如果成功则返回0,否则的话返回非0,对于check_call函数,如果执行成功,返回0,如果执行失败,抛出subrocess.CalledProcessError异常。如下所示:
In [5]: subprocess.check_call(['ls','-l'])
drwxr-xr-x. 2 root root 6 10月 31 23:04 公共
drwxr-xr-x. 2 root root 6 10月 31 23:04 模板
drwxr-xr-x. 2 root root 6 10月 31 23:04 视频
drwxr-xr-x. 2 root root 4096 10月 31 22:40 图片
drwxr-xr-x. 2 root root 6 10月 31 23:04 文档
drwxr-xr-x. 2 root root 6 10月 31 23:04 下载
drwxr-xr-x. 2 root root 6 10月 31 23:04 音乐
drwxr-xr-x. 2 root root 6 10月 31 15:27 桌面
Out[5]: 0
In [6]: subprocess.check_call('exit 1',shell=True)
-------------------------------------------------------------
CalledProcessError Traceback (most recent call last)
in
----> 1 subprocess.check_call('exit 1',shell=True)
/usr/local/python381/lib/python3.8/subprocess.py in check_call(*popenargs, **kwargs)
362 if cmd is None:
363 cmd = popenargs[0]
--> 364 raise CalledProcessError(retcode, cmd)
365 return 0
366
CalledProcessError: Command 'exit