ToB企服应用市场:ToB评测及商务社交产业平台

标题: Python模块学习:subprocess模块详解 [打印本页]

作者: 不到断气不罢休    时间: 2023-8-12 18:29
标题: Python模块学习:subprocess模块详解
一.subprocess模块

subprocess是Python 2.4中新增的一个模块,它允许你生成新的进程,连接到它们的 input/output/error 管道,并获取它们的返回(状态)码。这个模块的目的在于替换几个旧的模块和方法,如:
  1. os.system
  2. os.spawn*
复制代码
1.subprocess模块中的常用函数

函数描述subprocess.run()Python 3.5中新增的函数。执行指定的命令,等待命令执行完成后返回一个包含执行结果的CompletedProcess类subprocess.call()执行指定的命令,返回命令执行状态,其功能类似于os.system(cmd)。subprocess.check_call()Python 2.5中新增的函数。 执行指定的命令,如果执行成功则返回状态码,否则抛出异常。其功能等价于subprocess.run(…, check=True)。subprocess.check_output()Python 2.7中新增的的函数。执行指定的命令,如果执行状态码为0则返回命令执行结果,否则抛出异常。subprocess.getoutput(cmd)接收字符串格式的命令,执行命令并返回执行结果,其功能类似于os.popen(cmd).read()和commands.getoutput(cmd)。subprocess.getstatusoutput(cmd)执行cmd命令,返回一个元组(命令执行状态, 命令执行结果输出),其功能类似于commands.getstatusoutput()。说明:
1.在Python 3.5之后的版本中,官方文档中提倡通过subprocess.run()函数替代其他函数来使用subproccess模块的功能;
2.在Python 3.5之前的版本中,我们可以通过subprocess.call(),subprocess.getoutput()等上面列出的其他函数来使用subprocess模块的功能;
3.subprocess.run()、subprocess.call()、subprocess.check_call()和subprocess.check_output()都是通过对subprocess.Popen的封装来实现的高级函数,因此如果我们需要更复杂功能时,可以通过subprocess.Popen来完成。
4.subprocess.getoutput()和subprocess.getstatusoutput()函数是来自Python 2.x的commands模块的两个遗留函数。它们隐式的调用系统shell,并且不保证其他函数所具有的安全性和异常处理的一致性。另外,它们从Python 3.3.4开始才支持Windows平台。
2.上面各函数的定义及参数说明

函数参数列表:
  1. subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, universal_newlines=False)
  2. subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)
  3. subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None)
  4. subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False, timeout=None)
  5. subprocess.getstatusoutput(cmd)
  6. subprocess.getoutput(cmd)
复制代码
参数说明:
args: 要执行的shell命令,默认应该是一个字符串序列,如[‘df’, ‘-Th’]或(‘df’, ‘-Th’),也可以是一个字符串,如’df -Th’,但是此时需要把shell参数的值置为True。
shell: 如果shell为True,那么指定的命令将通过shell执行。如果我们需要访问某些shell的特性,如管道、文件名通配符、环境变量扩展功能,这将是非常有用的。当然,python本身也提供了许多类似shell的特性的实现,如glob、fnmatch、os.walk()、os.path.expandvars()、os.expanduser()和shutil等。
check: 如果check参数的值是True,且执行命令的进程以非0状态码退出,则会抛出一个CalledProcessError的异常,且该异常对象会包含 参数、退出状态码、以及stdout和stderr(如果它们有被捕获的话)。
stdout, stderr:input: 该参数是传递给Popen.communicate(),通常该参数的值必须是一个字节序列,如果universal_newlines=True,则其值应该是一个字符串。
universal_newlines: 该参数影响的是输入与输出的数据格式,比如它的值默认为False,此时stdout和stderr的输出是字节序列;当该参数的值设置为True时,stdout和stderr的输出是字符串。
3.subprocess.CompletedProcess类介绍

需要说明的是,subprocess.run()函数是Python3.5中新增的一个高级函数,其返回值是一个subprocess.CompletedPorcess类的实例,因此,subprocess.completedPorcess类也是Python 3.5中才存在的。它表示的是一个已结束进程的状态信息,它所包含的属性如下:
4.实例

subprocess.run()
  1. >>> subprocess.run(["ls", "-l"])  # doesn't capture output
  2. CompletedProcess(args=['ls', '-l'], returncode=0)
  3. >>> subprocess.run("exit 1", shell=True, check=True)
  4. Traceback (most recent call last):
  5.   ...
  6. subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
  7. >>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
  8. CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
  9. stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')
复制代码
subprocess.call()
  1. >>> subprocess.call(['ls',  '-l'])
  2. 总用量 160
  3. drwxr-xr-x  2 wader wader   4096 12月  7  2015 公共的
  4. drwxr-xr-x  2 wader wader   4096 12月  7  2015 模板
  5. drwxr-xr-x  2 wader wader   4096 12月  7  2015 视频
  6. drwxr-xr-x  2 wader wader   4096 12月  7  2015 图片
  7. drwxr-xr-x  2 wader wader   4096 12月  7  2015 文档
  8. drwxr-xr-x  2 wader wader   4096  4月 13  2016 下载
  9. drwxr-xr-x  2 wader wader   4096 12月  7  2015 音乐
  10. drwxr-xr-x  7 wader wader   4096  5月 26  2016 桌面
  11. 0
  12. >>> subprocess.call('ls -l', shell=True)
  13. 总用量 160
  14. drwxr-xr-x  2 wader wader   4096 12月  7  2015 公共的
  15. drwxr-xr-x  2 wader wader   4096 12月  7  2015 模板
  16. drwxr-xr-x  2 wader wader   4096 12月  7  2015 视频
  17. drwxr-xr-x  2 wader wader   4096 12月  7  2015 图片
  18. drwxr-xr-x  2 wader wader   4096 12月  7  2015 文档
  19. drwxr-xr-x  2 wader wader   4096  4月 13  2016 下载
  20. drwxr-xr-x  2 wader wader   4096 12月  7  2015 音乐
  21. drwxr-xr-x  7 wader wader   4096  5月 26  2016 桌面
  22. 0
  23. >>> subprocess.call(['ls',  '-l'], stdout=subprocess.DEVNULL)
  24. 0
  25. >>> subprocess.call(['ls',  '-l', '/test'])
  26. ls: 无法访问/test: 没有那个文件或目录
  27. 2
复制代码
suprocess.check_call()
  1. >>> subprocess.check_call(['ls',  '-l'])
  2. 总用量 160
  3. drwxr-xr-x  2 wader wader   4096 12月  7  2015 公共的
  4. drwxr-xr-x  2 wader wader   4096 12月  7  2015 模板
  5. drwxr-xr-x  2 wader wader   4096 12月  7  2015 视频
  6. drwxr-xr-x  2 wader wader   4096 12月  7  2015 图片
  7. drwxr-xr-x  2 wader wader   4096 12月  7  2015 文档
  8. drwxr-xr-x  2 wader wader   4096  4月 13  2016 下载
  9. drwxr-xr-x  2 wader wader   4096 12月  7  2015 音乐
  10. drwxr-xr-x  7 wader wader   4096  5月 26  2016 桌面
  11. 0
  12. >>> subprocess.check_call('ls -l', shell=True)
  13. 总用量 160
  14. drwxr-xr-x  2 wader wader   4096 12月  7  2015 公共的
  15. drwxr-xr-x  2 wader wader   4096 12月  7  2015 模板
  16. drwxr-xr-x  2 wader wader   4096 12月  7  2015 视频
  17. drwxr-xr-x  2 wader wader   4096 12月  7  2015 图片
  18. drwxr-xr-x  2 wader wader   4096 12月  7  2015 文档
  19. drwxr-xr-x  2 wader wader   4096  4月 13  2016 下载
  20. drwxr-xr-x  2 wader wader   4096 12月  7  2015 音乐
  21. drwxr-xr-x  7 wader wader   4096  5月 26  2016 桌面
  22. 0
  23. >>> subprocess.check_call('ls -l /test', shell=True)
  24. ls: 无法访问/test: 没有那个文件或目录
  25. Traceback (most recent call last):
  26.   File "<stdin>", line 1, in <module>
  27.   File "/usr/lib/python3.4/subprocess.py", line 557, in check_call
  28.     raise CalledProcessError(retcode, cmd)
  29. subprocess.CalledProcessError: Command 'ls -l /test' returned non-zero exit status 2
复制代码
subprocess.check_output()
  1. >>> ret = subprocess.check_output(['ls',  '-l'])
  2. >>> print(ret)
  3. b' \xe5\x85\xac\xe5\x85\xb1\xe7\x9a\x84\ndrwxr-xr-x  2 wader wader   4096 12\xe6\x9c\x88  7  2015 \xe6\xa8\xa1\xe6\x9d\xbf\ndrwxr-xr-x  2 wader wader   4096 12\xe6\x9c\x88  7  2015 \xe8\xa7\x86\xe9\xa2\x91\ndrwxr-xr-x  2 wader wader   4096 12\xe6\x9c\x88  7  2015 \xe5\x9b\xbe\xe7\x89\x87\ndrwxr-xr-x  2 wader wader   4096 12\xe6\x9c\x88  7  2015 \xe6\x96\x87\xe6\xa1\xa3\ndrwxr-xr-x  2 wader wader   4096  4\xe6\x9c\x88 13  2016 \xe4\xb8\x8b\xe8\xbd\xbd\ndrwxr-xr-x  2 wader wader   4096 12\xe6\x9c\x88  7  2015 \xe9\x9f\xb3\xe4\xb9\x90\ndrwxr-xr-x  7 wader wader   4096  5\xe6\x9c\x88 26  2016 \xe6\xa1\x8c\xe9\x9d\xa2\n'
  4. >>> ret = subprocess.check_output(['ls',  '-l'], universal_newlines=True)
  5. >>> print(ret)
  6. 总用量 160
  7. drwxr-xr-x  2 wader wader   4096 12月  7  2015 公共的
  8. drwxr-xr-x  2 wader wader   4096 12月  7  2015 模板
  9. drwxr-xr-x  2 wader wader   4096 12月  7  2015 视频
  10. drwxr-xr-x  2 wader wader   4096 12月  7  2015 图片
  11. drwxr-xr-x  2 wader wader   4096 12月  7  2015 文档
  12. drwxr-xr-x  2 wader wader   4096  4月 13  2016 下载
  13. drwxr-xr-x  2 wader wader   4096 12月  7  2015 音乐
  14. drwxr-xr-x  7 wader wader   4096  5月 26  2016 桌面
复制代码
subprocess.getoutput()与subprocess.getstatusoutput()
  1. >>> ret = subprocess.getoutput('ls -l')
  2. >>> print(ret)
  3. 总用量 160
  4. drwxr-xr-x  2 wader wader   4096 12月  7  2015 公共的
  5. drwxr-xr-x  2 wader wader   4096 12月  7  2015 模板
  6. drwxr-xr-x  2 wader wader   4096 12月  7  2015 视频
  7. drwxr-xr-x  2 wader wader   4096 12月  7  2015 图片
  8. drwxr-xr-x  2 wader wader   4096 12月  7  2015 文档
  9. drwxr-xr-x  2 wader wader   4096  4月 13  2016 下载
  10. drwxr-xr-x  2 wader wader   4096 12月  7  2015 音乐
  11. drwxr-xr-x  7 wader wader   4096  5月 26  2016 桌面
  12. >>> retcode, output = subprocess.getstatusoutput('ls -l')
  13. >>> print(retcode)
  14. 0
  15. >>> print(output)
  16. 总用量 160
  17. drwxr-xr-x  2 wader wader   4096 12月  7  2015 公共的
  18. drwxr-xr-x  2 wader wader   4096 12月  7  2015 模板
  19. drwxr-xr-x  2 wader wader   4096 12月  7  2015 视频
  20. drwxr-xr-x  2 wader wader   4096 12月  7  2015 图片
  21. drwxr-xr-x  2 wader wader   4096 12月  7  2015 文档
  22. drwxr-xr-x  2 wader wader   4096  4月 13  2016 下载
  23. drwxr-xr-x  2 wader wader   4096 12月  7  2015 音乐
  24. drwxr-xr-x  7 wader wader   4096  5月 26  2016 桌面
  25. >>> retcode, output = subprocess.getstatusoutput('ls -l /test')
  26. >>> print(retcode)
  27. 2
  28. >>> print(output)
  29. ls: 无法访问/test: 没有那个文件或目录
复制代码
二.subprocess.Popen介绍

该类用于在一个新的进程中执行一个子程序。前面我们提到过,上面介绍的这些函数都是基于subprocess.Popen类实现的,通过使用这些被封装后的高级函数可以很方面的完成一些常见的需求。由于subprocess模块底层的进程创建和管理是由Popen类来处理的,因此,当我们无法通过上面哪些高级函数来实现一些不太常见的功能时就可以通过subprocess.Popen类提供的灵活的api来完成。
1 subprocess.Popen的构造函数
  1. class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None,
  2.     preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False,
  3.     startup_info=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())
复制代码
参数说明:
2.subprocess.Popen类的实例可调用的方法

方法描述Popen.poll()用于检查子进程(命令)是否已经执行结束,没结束返回None,结束后返回状态码。Popen.wait(timeout=None)等待子进程结束,并返回状态码;如果在timeout指定的秒数之后进程还没有结束,将会抛出一个TimeoutExpired异常。Popen.communicate(input=None, timeout=None)该方法可用来与进程进行交互,比如发送数据到stdin,从stdout和stderr读取数据,直到到达文件末尾。Popen.send_signal(signal)发送指定的信号给这个子进程。Popen.terminate()停止该子进程。Popen.kill()杀死该子进程。关于communicate()方法的说明:
3 subprocess.Popen使用实例

实例1
  1. >>> import subprocess
  2. >>>
  3. >>> p = subprocess.Popen('df -Th', stdout=subprocess.PIPE, shell=True)
  4. >>> print(p.stdout.read())
  5. Filesystem     Type      Size  Used Avail Use% Mounted on
  6. /dev/vda1      ext4       40G   12G   26G  31% /
  7. devtmpfs       devtmpfs  3.9G     0  3.9G   0% /dev
  8. tmpfs          tmpfs     3.9G     0  3.9G   0% /dev/shm
  9. tmpfs          tmpfs     3.9G  386M  3.5G  10% /run
  10. tmpfs          tmpfs     3.9G     0  3.9G   0% /sys/fs/cgroup
  11. tmpfs          tmpfs     783M     0  783M   0% /run/user/0
  12. tmpfs          tmpfs     783M     0  783M   0% /run/user/1000
复制代码
实例2
  1. >>> obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  2. >>> obj.stdin.write('print(1) \n')
  3. >>> obj.stdin.write('print(2) \n')
  4. >>> obj.stdin.write('print(3) \n')
  5. >>> out,err = obj.communicate()
  6. >>> print(out)
  7. 1
  8. 2
  9. 3
  10. >>> print(err)
复制代码
实例3
  1. >>> obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  2. >>> out,err = obj.communicate(input='print(1) \n')
  3. >>> print(out)
  4. 1
  5. >>> print(err)
复制代码
实例4
实现类似df -Th | grep data命令的功能,实际上就是实现shell中管道的共功能。
  1. >>>
  2. >>> p1 = subprocess.Popen(['df', '-Th'], stdout=subprocess.PIPE)
  3. >>> p2 = subprocess.Popen(['grep', 'data'], stdin=p1.stdout, stdout=subprocess.PIPE)
  4. >>> out,err = p2.communicate()
  5. >>> print(out)
  6. /dev/vdb1      ext4      493G  4.8G  463G   2% /data
  7. /dev/vdd1      ext4     1008G  420G  537G  44% /data1
  8. /dev/vde1      ext4      985G  503G  432G  54% /data2
  9. #Python小白学习交流群:711312441
  10. >>> print(err)
  11. None
复制代码
三.总结

那么我们到底该用哪个模块、哪个函数来执行命令与系统及系统进行交互呢?下面我们来做个总结:
首先应该知道的是,Python2.4版本引入了subprocess模块用来替换os.system()、os.popen()、os.spawn*()等函数以及commands模块;也就是说如果你使用的是Python 2.4及以上的版本就应该使用subprocess模块了。
如果你的应用使用的Python 2.4以上,但是是Python 3.5以下的版本,Python官方给出的建议是使用subprocess.call()函数。Python 2.5中新增了一个subprocess.check_call()函数,Python 2.7中新增了一个subprocess.check_output()函数,这两个函数也可以按照需求进行使用。
如果你的应用使用的是Python 3.5及以上的版本(目前应该还很少),Python官方给出的建议是尽量使用subprocess.run()函数。
当subprocess.call()、subprocess.check_call()、subprocess.check_output()和subprocess.run()这些高级函数无法满足需求时,我们可以使用subprocess.Popen类来实现我们需要的复杂功能。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4