1. def run(*popenargs,
  2. input=None, capture_output=False, timeout=None, check=False, **kwargs):
  3. """Run command with arguments and return a CompletedProcess instance.
  4.  
  5. The returned instance will have attributes args, returncode, stdout and
  6. stderr. By default, stdout and stderr are not captured, and those attributes
  7. will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them.
  8.  
  9. If check is True and the exit code was non-zero, it raises a
  10. CalledProcessError. The CalledProcessError object will have the return code
  11. in the returncode attribute, and output & stderr attributes if those streams
  12. were captured.
  13.  
  14. If timeout is given, and the process takes too long, a TimeoutExpired
  15. exception will be raised.
  16.  
  17. There is an optional argument "input", allowing you to
  18. pass bytes or a string to the subprocess's stdin. If you use this argument
  19. you may not also use the Popen constructor's "stdin" argument, as
  20. it will be used internally.
  21.  
  22. By default, all communication is in bytes, and therefore any "input" should
  23. be bytes, and the stdout and stderr will be bytes. If in text mode, any
  24. "input" should be a string, and stdout and stderr will be strings decoded
  25. according to locale encoding, or by "encoding" if set. Text mode is
  26. triggered by setting any of text, encoding, errors or universal_newlines.
  27.  
  28. The other arguments are the same as for the Popen constructor.
  29. """
  30. if input is not None:
  31. if 'stdin' in kwargs:
  32. raise ValueError('stdin and input arguments may not both be used.')
  33. kwargs['stdin'] = PIPE
  34.  
  35. if capture_output:
  36. if ('stdout' in kwargs) or ('stderr' in kwargs):
  37. raise ValueError('stdout and stderr arguments may not be used '
  38. 'with capture_output.')
  39. kwargs['stdout'] = PIPE
  40. kwargs['stderr'] = PIPE
  41.  
  42. with Popen(*popenargs, **kwargs) as process:
  43. try:
  44. stdout, stderr = process.communicate(input, timeout=timeout)
  45. except TimeoutExpired:
  46. process.kill()
  47. stdout, stderr = process.communicate()
  48. raise TimeoutExpired(process.args, timeout, output=stdout,
  49. stderr=stderr)
  50. except: # Including KeyboardInterrupt, communicate handled that.
  51. process.kill()
  52. # We don't call process.wait() as .__exit__ does that for us.
  53. raise
  54. retcode = process.poll()
  55. if check and retcode:
  56. raise CalledProcessError(retcode, process.args,
  57. output=stdout, stderr=stderr)
  58. return CompletedProcess(process.args, retcode, stdout, stderr)

  可以看到返回的是一个completeProcess对象

  1. class CompletedProcess(object):
  2. """A process that has finished running.
  3.  
  4. This is returned by run().
  5.  
  6. Attributes:
  7. args: The list or str args passed to run().
  8. returncode: The exit code of the process, negative for signals.
  9. stdout: The standard output (None if not captured).
  10. stderr: The standard error (None if not captured).
  11. """
  12. def __init__(self, args, returncode, stdout=None, stderr=None):
  13. self.args = args
  14. self.returncode = returncode
  15. self.stdout = stdout
  16. self.stderr = stderr
  17.  
  18. def __repr__(self):
  19. args = ['args={!r}'.format(self.args),
  20. 'returncode={!r}'.format(self.returncode)]
  21. if self.stdout is not None:
  22. args.append('stdout={!r}'.format(self.stdout))
  23. if self.stderr is not None:
  24. args.append('stderr={!r}'.format(self.stderr))
  25. return "{}({})".format(type(self).__name__, ', '.join(args))
  26.  
  27. def check_returncode(self):
  28. """Raise CalledProcessError if the exit code is non-zero."""
  29. if self.returncode:
  30. raise CalledProcessError(self.returncode, self.args, self.stdout,
  31. self.stderr)

  

所以调用获取最终returncode可以使用

sub=subproccess.run(xxxxx)

returncode,out,err,args=sub.returncode,sub.stdout,sub.stderr,sub.args

  1. #!/usr/bin/python3
  2. # coding=gbk
  3. import os
  4. import sys
  5. curPath = os.path.abspath(os.path.dirname(__file__))
  6. rootPath = os.path.split(curPath)[0]
  7. sys.path.append(rootPath)
  8. import subprocess
  9. import platform
  10. from src import logutils
  11.  
  12. log=logutils.logger("app",rootstdout=True,handlerList=['I','E'])
  13. """
      if check=True then returncode ==0 return stdout normal,
      returncode!=0 rasise callProcessError ,check=False nothing to do
    """
  14. def subprocess_run():
  15. str_shell='df -m &&netstat -ntslp|grep 11111'
  16. CompletedProcessObject=subprocess.run(args=str_shell,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,
  17. stderr=subprocess.PIPE,universal_newlines=True,timeout=10,check=False)
  18. if CompletedProcessObject:
  19. code,out,err=CompletedProcessObject.returncode,CompletedProcessObject.stdout,CompletedProcessObject.stderr
  20.  
  21. if code ==0:
  22. if out:
  23. #log.info("执行isok!!!!")
  24. log.info(out)
  25. return out
  26. if err:
  27. log.error(err)
  28. return err
  29. else:
  30. if code ==1:
  31. log.error("语法输出对象为空")
  32. else:
  33. #log.info(code)
  34. raise subprocess.CalledProcessError(code,str_shell)
  35.  
  36. def run():
  37. str_shell='df -m && netstat -ntlp'
  38. sub=subprocess.Popen(args=str_shell,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,
  39. stderr=subprocess.PIPE,universal_newlines=True)
  40. out,err=sub.communicate()
  41. #res=sub.stdout.readlines()
  42.  
  43. if sub.returncode == 0:
  44. #log.info("returncode is 0,执行输出正常")
  45. if out:
  46. log.info("执行输出正常")
  47. log.info(out)
  48. if err:
  49. log.error("出现异常")
  50. log.error(err,exc_info=True)
  51. else:
  52. if sub.returncode == 1:
  53. log.error("执行shell对象结果有空")
  54. else:
  55. raise subprocess.CalledProcessError(sub.returncode, str_shell)
  56.  
  57. def operate_sys():
  58. plat_tuple=platform.architecture()
  59. system=platform.system()
  60. plat_version=platform.platform()
  61. if system == 'Windows':
  62. return system,plat_version
  63. # log.info('this is windows system')
  64. # log.info('version is: '+plat_version)
  65. elif system == 'Linux':
  66. return system,plat_version
  67. # log.info('this is linux system ')
  68. # log.info('version is: '+plat_version)
  69.  
  70. if __name__ == '__main__':
  71. subprocess_run()

 正常check=True时 returncode=0代表结果都输出正常

[root@hostuser src]# python3 subprocess_popen.py
[INFO]2019-05-19 21:01:59 Sun --app-- subprocess_popen.py:
执行isok!!!!
[INFO]2019-05-19 21:01:59 Sun --app-- subprocess_popen.py:
Filesystem 1M-blocks Used Available Use% Mounted on
/dev/mapper/centos-root 27627 8652 18975 32% /
devtmpfs 894 0 894 0% /dev
tmpfs 910 1 910 1% /dev/shm
tmpfs 910 11 900 2% /run
tmpfs 910 0 910 0% /sys/fs/cgroup
/dev/sda1 1014 232 783 23% /boot
tmpfs 182 1 182 1% /run/user/42
tmpfs 182 0 182 0% /run/user/0
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.81.129 netmask 255.255.255.0 broadcast 192.168.81.255
inet6 fe80::f08c:a9:42b2:6ec4 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:11:d6:35 txqueuelen 1000 (Ethernet)
RX packets 16609 bytes 1344727 (1.2 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 9525 bytes 1168830 (1.1 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536
inet 127.0.0.1 netmask 255.0.0.0
inet6 ::1 prefixlen 128 scopeid 0x10<host>
loop txqueuelen 1000 (Local Loopback)
RX packets 194415 bytes 161261315 (153.7 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 194415 bytes 161261315 (153.7 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

virbr0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 192.168.122.1 netmask 255.255.255.0 broadcast 192.168.122.255
ether 52:54:00:4a:9f:2c txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

正常check=True时抛出异常1代表执行结果有空:
[root@hostuser src]# python3 subprocess_popen.py
Traceback (most recent call last):
File "subprocess_popen.py", line 73, in <module>
subprocess_run()
File "subprocess_popen.py", line 17, in subprocess_run
stderr=subprocess.PIPE,universal_newlines=True,timeout=10,check=True)
File "/usr/local/lib/python3.7/subprocess.py", line 487, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command 'df -m &&netstat -ntslp|grep 11111' returned non-zero exit status 1.

check=False:异常时则如果你不做处理返回空

正常还是返回stdout结果

subprocess.run()用法python3.7的更多相关文章

  1. 模块sys, os, glob, pickle, subprocess常见用法

    参考python常用标准库 http://blog.51cto.com/lizhenliang/1872538 一. sys   1. sys.argv 脚本名1.py, 命令行中执行python 1 ...

  2. [Python3]subprocess.check_output() 在python3的输出为bytes而非string,在实际使用过程中得增加一个解码过程decode(),不然会有问题

    按以往python2的习惯编码输出报错 #-*- coding:utf-8 -*- ''' Created on 2018年7月21日 @author: lenovo ''' import os im ...

  3. set的特性和基本用法——python3.6

    特性 无序,不重复的数据组合,用{}表示,eg:{1,2,3,4,5,6} 用途 去重,把一个列表变成集合,就自动去重了 关系测试,测试两组数据之间的交集,差集,并集,对称差集,包含(子集和超集,相交 ...

  4. python笔记-9(subprocess模块、面向对象、socket入门)

    一.subprocess 模块 1.了解os.system()与os.popen的区别及不足 1.1 os.system()可以执行系统指令,将结果直接输出到屏幕,同时可以将指令是否执行成功的状态赋值 ...

  5. Python中调用Linux命令并获取返回值

    方法一.使用os模块的system方法:os.system(cmd),其返回值是shell指令运行后返回的状态码,int类型,0表示shell指令成功执行,256/512表示未找到,该方法适用于she ...

  6. Python调用shell命令常用方法

    Python调用shell指令 方法一.使用os模块的system方法:os.system(cmd),其返回值是shell指令运行后返回的状态码,int类型,0表示shell指令成功执行,256表示未 ...

  7. python3之xml&ConfigParser&hashlib&Subprocess&logging模块

    1.xml模块 XML 指可扩展标记语言(eXtensible Markup Language),标准通用标记语言的子集,是一种用于标记电子文件使其具有结构性的标记语言. XML 被设计用来传输和存储 ...

  8. python3之subprocess常见方法使用

    一.常见subprocess方法 1.subprocess.getstatusoutput(cmd) 官方解释: Return (exitcode, output) of executing cmd ...

  9. python3 subprocess模块

    当我们在执行python程序的时候想要执行系统shell可以使用subprocess,这时可以新起一个进程来执行系统的shell命令,python3常用的有subprocess.run()和subpr ...

随机推荐

  1. .NET知识梳理——2.反射

    1. 反射 1.1        DLL-IL-Metadata-反射 DLL:程序集,包含IL 和Metadada IL:面向对象中间语言(不太好阅读) Metadata描述了dll.exe中的各种 ...

  2. flex space-between最后一行对齐问题的解决方案

    背景 常见的一个图文列表设计,通常是这样的,两端顶着容器,中间的间距平均分,如下图的某东商品列表的设计: 列表是这样自适应的,当视窗足够放多少个商品就放多少个,然后各个商品项目之间的间距平均分.由于每 ...

  3. 命名元组nametuple

    # coding:utf-8 from collections import namedtuple Student = namedtuple('Student', ['no', 'name', 'ag ...

  4. 吴裕雄 python 机器学习——集成学习梯度提升决策树GradientBoostingRegressor回归模型

    import numpy as np import matplotlib.pyplot as plt from sklearn import datasets,ensemble from sklear ...

  5. Servlet转发

    可以使用ServletContext中的getRequestDispatcher(url).forward(request, response)方法进行转发 myservlet2.java publi ...

  6. 并发之CountDownLatch用法详解

    概念 CountDownLatch 是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程执行完后再执行.例如,应用程序的主线程希望在负责启动框架服务的线程已经启动所有的框架服务之后执行. Co ...

  7. 关于MultiAutoCompleteTextView的用法:多文本匹配

  8. Laravel 虚拟开发环境 Homestead 密码

    默认数据库账号密码账号: homestead 密码:secret 默认 ssh 账号密码账号:vagrant 密码:vagrant创建默认 root 用户sudo passwd root

  9. SVN代码迁移到GITlab

    ==================================================================================================== ...

  10. 萌新深度学习与Pytorch入门记录(一):Win10下环境安装

    深度学习从入门到入土,安装软件及配置环境踩了不少坑,过程中参考了多处博主给的解决方法,遂整合一下自己的采坑记录. (若遇到不一样的错误,请参考其他博主答案解决) 笔者电脑系统为win10系统,在此环境 ...