Operation of python subprocess pipe real time output log
- 2021-08-17 00:13:26
- OfStack
* 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 means in progress
while p.poll() is None: < br > out = p. stdout. readline () < br > if out! = "": < br > print out
Additional knowledge: python executes commands through subprocess. Popen to redirect real-time output
Execute a command
import subprocess
import sys
# Common code
GBK = 'gbk'
UTF8 = 'utf-8'
# Decoding mode, 1 Like py File executes as utf-8 , cmd The command is 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))
Execute the. py file
import subprocess
import sys
# Common code
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))