def run(*popenargs,
input=None, capture_output=False, timeout=None, check=False, **kwargs):
"""Run command with arguments and return a CompletedProcess instance. The returned instance will have attributes args, returncode, stdout and
stderr. By default, stdout and stderr are not captured, and those attributes
will be None. Pass stdout=PIPE and/or stderr=PIPE in order to capture them. If check is True and the exit code was non-zero, it raises a
CalledProcessError. The CalledProcessError object will have the return code
in the returncode attribute, and output & stderr attributes if those streams
were captured. If timeout is given, and the process takes too long, a TimeoutExpired
exception will be raised. There is an optional argument "input", allowing you to
pass bytes or a string to the subprocess's stdin. If you use this argument
you may not also use the Popen constructor's "stdin" argument, as
it will be used internally. By default, all communication is in bytes, and therefore any "input" should
be bytes, and the stdout and stderr will be bytes. If in text mode, any
"input" should be a string, and stdout and stderr will be strings decoded
according to locale encoding, or by "encoding" if set. Text mode is
triggered by setting any of text, encoding, errors or universal_newlines. The other arguments are the same as for the Popen constructor.
"""
if input is not None:
if 'stdin' in kwargs:
raise ValueError('stdin and input arguments may not both be used.')
kwargs['stdin'] = PIPE if capture_output:
if ('stdout' in kwargs) or ('stderr' in kwargs):
raise ValueError('stdout and stderr arguments may not be used '
'with capture_output.')
kwargs['stdout'] = PIPE
kwargs['stderr'] = PIPE with Popen(*popenargs, **kwargs) as process:
try:
stdout, stderr = process.communicate(input, timeout=timeout)
except TimeoutExpired:
process.kill()
stdout, stderr = process.communicate()
raise TimeoutExpired(process.args, timeout, output=stdout,
stderr=stderr)
except: # Including KeyboardInterrupt, communicate handled that.
process.kill()
# We don't call process.wait() as .__exit__ does that for us.
raise
retcode = process.poll()
if check and retcode:
raise CalledProcessError(retcode, process.args,
output=stdout, stderr=stderr)
return CompletedProcess(process.args, retcode, stdout, stderr)

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

class CompletedProcess(object):
"""A process that has finished running. This is returned by run(). Attributes:
args: The list or str args passed to run().
returncode: The exit code of the process, negative for signals.
stdout: The standard output (None if not captured).
stderr: The standard error (None if not captured).
"""
def __init__(self, args, returncode, stdout=None, stderr=None):
self.args = args
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr def __repr__(self):
args = ['args={!r}'.format(self.args),
'returncode={!r}'.format(self.returncode)]
if self.stdout is not None:
args.append('stdout={!r}'.format(self.stdout))
if self.stderr is not None:
args.append('stderr={!r}'.format(self.stderr))
return "{}({})".format(type(self).__name__, ', '.join(args)) def check_returncode(self):
"""Raise CalledProcessError if the exit code is non-zero."""
if self.returncode:
raise CalledProcessError(self.returncode, self.args, self.stdout,
self.stderr)

  

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

sub=subproccess.run(xxxxx)

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

#!/usr/bin/python3
# coding=gbk
import os
import sys
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)
import subprocess
import platform
from src import logutils log=logutils.logger("app",rootstdout=True,handlerList=['I','E'])
"""
  if check=True then returncode ==0 return stdout normal,
  returncode!=0 rasise callProcessError ,check=False nothing to do
"""
def subprocess_run():
str_shell='df -m &&netstat -ntslp|grep 11111'
CompletedProcessObject=subprocess.run(args=str_shell,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,
stderr=subprocess.PIPE,universal_newlines=True,timeout=10,check=False)
if CompletedProcessObject:
code,out,err=CompletedProcessObject.returncode,CompletedProcessObject.stdout,CompletedProcessObject.stderr if code ==0:
if out:
#log.info("执行isok!!!!")
log.info(out)
return out
if err:
log.error(err)
return err
else:
if code ==1:
log.error("语法输出对象为空")
else:
#log.info(code)
raise subprocess.CalledProcessError(code,str_shell) def run():
str_shell='df -m && netstat -ntlp'
sub=subprocess.Popen(args=str_shell,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,
stderr=subprocess.PIPE,universal_newlines=True)
out,err=sub.communicate()
#res=sub.stdout.readlines() if sub.returncode == 0:
#log.info("returncode is 0,执行输出正常")
if out:
log.info("执行输出正常")
log.info(out)
if err:
log.error("出现异常")
log.error(err,exc_info=True)
else:
if sub.returncode == 1:
log.error("执行shell对象结果有空")
else:
raise subprocess.CalledProcessError(sub.returncode, str_shell) def operate_sys():
plat_tuple=platform.architecture()
system=platform.system()
plat_version=platform.platform()
if system == 'Windows':
return system,plat_version
# log.info('this is windows system')
# log.info('version is: '+plat_version)
elif system == 'Linux':
return system,plat_version
# log.info('this is linux system ')
# log.info('version is: '+plat_version) if __name__ == '__main__':
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. 虚拟机安装的ubuntu不能联网解决

    安装双系统从没遇到的问题,再虚拟机上遇到了不能联网的问题: 下面给出我的解决方法(win10系统.ubuntu 16.04) 我的电脑-管理-设备管理器 看是否虚拟机的虚拟网卡在: 在去设置-控制面板 ...

  2. 设置DataGridView的单元格颜色

    RowPrePaint事件: private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArg ...

  3. Docker镜像加速,设置国内源

    源地址设置 在 /etc/docker/daemon.json 中写入如下内容(如果文件不存在请新建该文件) { "registry-mirrors": [ "https ...

  4. 【visio】数据可视化 - 形状数据

    visio在对数据处理方面也是有一整套的设施,用户可以用visio存储.管理对象数据,利用数据驱动图形设计,让数据形象化,并在团队沟通的时候清晰地展示数据,沟通数据. 1.属性 每个图形都可以设置多个 ...

  5. NUMPY的学习之路(2)——索引,合并,分割,赋值

    一.索引 1.1numpy数组的转置 A=np.arange(3,15).reshape(3,4) print(A) print(A[2][0]) print(A[2,1]) print(A[2,:] ...

  6. 前端——语言——Core JS——《The good part》读书笔记——第九,十章节(Style,Good Features)

    第九章节 本章节不再介绍知识点,而是作者在提倡大家培养良好的编码习惯,使用Good parts of JS,避免Bad parts of JS.它是一篇文章. 本文的1-3段阐述应用在开发过程中总会遇 ...

  7. Python单例

    01. 单例设计模式 设计模式 设计模式 是 前人工作的总结和提炼,通常,被人们广泛流传的设计模式都是针对 某一特定问题 的成熟的解决方案 使用 设计模式 是为了可重用代码.让代码更容易被他人理解.保 ...

  8. windows安装jenkins及ant/maven/jdk配置

    一.jenkins安装 下载地址:https://jenkins.io/download/,下载下来为一个war文件 (1)第一种启动方式,电脑一启动,jenkins会自动运行 命运行运行 java  ...

  9. VMware克隆centos后需要进行修改配置的地方

    1. 首先在VMware中通过复制现在状态的虚拟机或者快照形式的虚拟机,选择完整复制文件进行克隆. 2.打开克隆的虚拟机之后,需要修改主机名和相应的hosts表 2.1 修改主机名 输入  vi /e ...

  10. C++ string类的使用

    C++ string的使用 在了解如何使用string类之前,我们先来看看C语言中使用字符串有多麻烦: 调用头文件:cstring 定义一个C字符串: char str1[51]="Hell ...