def run():
str_shell='ipconfig'
sub=subprocess.Popen(args=str_shell,shell=True,stdin=subprocess.PIPE,stdout=subprocess.PIPE,
stderr=subprocess.PIPE,universal_newlines=True)
try:
out,err=sub.communicate(timeout=15)
except TimeoutExpired:
sub.kill()
out, err = sub.communicate()
#res=sub.stdout.readlines()

if sub.returncode == 0:
if out:
#log.info("执行输出正常")
log.info(out)
return 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)

  

[root@hostuser src]# python3 subprocess_popen.py
[INFO]2019-05-18 23:39:07 Sat --app-- subprocess_popen.py:
<class 'str'>
[INFO]2019-05-18 23:39:07 Sat --app-- subprocess_popen.py:
Filesystem 1M-blocks Used Available Use% Mounted on
/dev/mapper/centos-root 27627 8627 19000 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
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 127.0.0.1:9100 0.0.0.0:* LISTEN 6481/node_exporter
tcp 0 0 0.0.0.0:111 0.0.0.0:* LISTEN 1/systemd
tcp 0 0 127.0.0.1:8080 0.0.0.0:* LISTEN 7057/unicorn master
tcp 0 0 127.0.0.1:9168 0.0.0.0:* LISTEN 6505/ruby
tcp 0 0 192.168.122.1:53 0.0.0.0:* LISTEN 9232/dnsmasq
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 7211/sshd
tcp 0 0 127.0.0.1:631 0.0.0.0:* LISTEN 7212/cupsd
tcp 0 0 127.0.0.1:25 0.0.0.0:* LISTEN 7459/master
tcp 0 0 127.0.0.1:6010 0.0.0.0:* LISTEN 52237/sshd: root@pt
tcp 0 0 127.0.0.1:6011 0.0.0.0:* LISTEN 57561/sshd: root@pt
tcp 0 0 0.0.0.0:8060 0.0.0.0:* LISTEN 6479/nginx: master
tcp 0 0 0.0.0.0:8989 0.0.0.0:* LISTEN 6479/nginx: master
tcp 0 0 127.0.0.1:9121 0.0.0.0:* LISTEN 6485/redis_exporter
tcp 0 0 127.0.0.1:9090 0.0.0.0:* LISTEN 6472/prometheus
tcp 0 0 127.0.0.1:9187 0.0.0.0:* LISTEN 6494/postgres_expor
tcp6 0 0 :::111 :::* LISTEN 1/systemd
tcp6 0 0 ::1:9168 :::* LISTEN 6505/ruby
tcp6 0 0 :::22 :::* LISTEN 7211/sshd
tcp6 0 0 :::23 :::* LISTEN 35527/xinetd
tcp6 0 0 ::1:631 :::* LISTEN 7212/cupsd
tcp6 0 0 ::1:25 :::* LISTEN 7459/master
tcp6 0 0 ::1:6010 :::* LISTEN 52237/sshd: root@pt
tcp6 0 0 ::1:6011 :::* LISTEN 57561/sshd: root@pt
NoneType: None
[root@hostuser src]#