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)