欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python subprocess pipe 实时输出日志的操作

程序员文章站 2022-06-27 17:49:57
* test11.pyimport timeprint "1"time.sleep(2)print "1"time.sleep(2)print "1"time.sleep(2)print "1"* t...

* test11.py

import time
print "1"
time.sleep(2)
print "1"
time.sleep(2)
print "1"
time.sleep(2)
print "1"

* test.py

import subprocess

p = subprocess.popen("python test11.py", shell=true, stdout=subprocess.pipe)

# none表示正在执行中

while p.poll() is none: <br>  out = p.stdout.readline() <br>  if out != "": <br>    print out

补充知识:python 通过 subprocess.popen执行命令,重定向实时输出

执行命令

import subprocess
import sys

# 常用编码
gbk = 'gbk'
utf8 = 'utf-8'

# 解码方式,一般 py 文件执行为utf-8 ,cmd 命令为 gbk
current_encoding = gbk
popen = subprocess.popen('ping www.baidu.com', shell = true,
             stdout = subprocess.pipe,
             stderr = subprocess.pipe,
             bufsize = 1)
out,err = popen.communicate()
print('std_out: ' + out)
print('std_err: ' + err)
print('returncode: ' + str(popen.returncode))

执行 .py文件

import subprocess
import sys

# 常用编码
gbk = 'gbk'
utf8 = 'utf-8'

current_encoding = utf8 
popen = subprocess.popen('python d:\code\test.py',
             stdout = subprocess.pipe,
             stderr = subprocess.pipe,
             bufsize = 1)
out,err = popen.communicate()
print('std_out: ' + out)
print('std_err: ' + err)
print('returncode: ' + str(popen.returncode))

以上这篇python subprocess pipe 实时输出日志的操作就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。