当前位置:   article > 正文

subprocess.run()用法python3.7

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

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

 

  1. class CompletedProcess(object):
  2. """A process that has finished running.
  3. This is returned by run().
  4. Attributes:
  5. args: The list or str args passed to run().
  6. returncode: The exit code of the process, negative for signals.
  7. stdout: The standard output (None if not captured).
  8. stderr: The standard error (None if not captured).
  9. """
  10. def __init__(self, args, returncode, stdout=None, stderr=None):
  11. self.args = args
  12. self.returncode = returncode
  13. self.stdout = stdout
  14. self.stderr = stderr
  15. def __repr__(self):
  16. args = ['args={!r}'.format(self.args),
  17. 'returncode={!r}'.format(self.returncode)]
  18. if self.stdout is not None:
  19. args.append('stdout={!r}'.format(self.stdout))
  20. if self.stderr is not None:
  21. args.append('stderr={!r}'.format(self.stderr))
  22. return "{}({})".format(type(self).__name__, ', '.join(args))
  23. def check_returncode(self):
  24. """Raise CalledProcessError if the exit code is non-zero."""
  25. if self.returncode:
  26. raise CalledProcessError(self.returncode, self.args, self.stdout,
  27. 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. log=logutils.logger("app",rootstdout=True,handlerList=['I','E'])
  12. """   if check=True then returncode ==0 return stdout normal,  returncode!=0 rasise callProcessError ,check=False nothing to do"""
  13. def subprocess_run():
  14. str_shell='df -m &&netstat -ntslp|grep 11111'
  15. CompletedProcessObject=subprocess.run(args=str_shell,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,
  16. stderr=subprocess.PIPE,universal_newlines=True,timeout=10,check=False)
  17. if CompletedProcessObject:
  18. code,out,err=CompletedProcessObject.returncode,CompletedProcessObject.stdout,CompletedProcessObject.stderr
  19. if code ==0:
  20. if out:
  21. #log.info("执行isok!!!!")
  22. log.info(out)
  23. return out
  24. if err:
  25. log.error(err)
  26. return err
  27. else:
  28. if code ==1:
  29. log.error("语法输出对象为空")
  30. else:
  31. #log.info(code)
  32. raise subprocess.CalledProcessError(code,str_shell)
  33. def run():
  34. str_shell='df -m && netstat -ntlp'
  35. sub=subprocess.Popen(args=str_shell,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,
  36. stderr=subprocess.PIPE,universal_newlines=True)
  37. out,err=sub.communicate()
  38. #res=sub.stdout.readlines()
  39. if sub.returncode == 0:
  40. #log.info("returncode is 0,执行输出正常")
  41. if out:
  42. log.info("执行输出正常")
  43. log.info(out)
  44. if err:
  45. log.error("出现异常")
  46. log.error(err,exc_info=True)
  47. else:
  48. if sub.returncode == 1:
  49. log.error("执行shell对象结果有空")
  50. else:
  51. raise subprocess.CalledProcessError(sub.returncode, str_shell)
  52. def operate_sys():
  53. plat_tuple=platform.architecture()
  54. system=platform.system()
  55. plat_version=platform.platform()
  56. if system == 'Windows':
  57. return system,plat_version
  58. # log.info('this is windows system')
  59. # log.info('version is: '+plat_version)
  60. elif system == 'Linux':
  61. return system,plat_version
  62. # log.info('this is linux system ')
  63. # log.info('version is: '+plat_version)
  64. if __name__ == '__main__':
  65. 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结果

 

转载于:https://www.cnblogs.com/SunshineKimi/p/10889145.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/218874
推荐阅读
相关标签
  

闽ICP备14008679号