1. 程式人生 > 程式設計 >python subprocess pipe 實時輸出日誌的操作

python subprocess pipe 實時輸出日誌的操作

* 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',err = popen.communicate()
print('std_out: ' + out)
print('std_err: ' + err)
print('returncode: ' + str(popen.returncode))

以上這篇python subprocess pipe 實時輸出日誌的操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。