Python 实时获取 CMD 命令输出结果,并处理中文乱码

本贴最后更新于 1464 天前,其中的信息可能已经天翻地覆

Python自动化测试过程中,可能需要执行CMD命令,并获取执行命令后的输出内容,对于使用中文操作系统的我们来说,遇到CMD命令输出结果包含中文内容是很正常的,这里就需要解决中文的编码问题,CMD默认的输出编码是GBK,我们可以使用GBK解码,但UTF-8的编码也是我们常用的,比如Python程序打印输出为中文时,就是UTF-8。我在调试代码的时候发现,Windows系统自带命令的输出内容如果包含中文,需使用GBK解码而不能使用UTF-8,而Python程序输出打印包含中文时需使用UTF-8来解码,下面是一个样例。

带有延时功能的打印包含中文内容的Python程序:

# -*- coding: utf -8 -*-
# C:\Users\Administrator\Desktop\hello.py

import time

for i in range(10):
	print("Hello " + str(i))
	print("我喜欢 Python!")
	time.sleep(1)  # 延迟1秒

调试程序,不论是GBK还是UTF-8的输出,都可以顺利解决:

import subprocess

file = r'C:\Users\Administrator\Desktop\hello.py'

def printCmd(cmd):

    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    while True:
        result = p.stdout.readline()  #默认获取到的是二进制内容
        if result != b'':  #获取内容不为空时
            try:
                print(result.decode('gbk').strip('\r\n'))  #处理GBK编码的输出,去掉结尾换行
            except:
                print(result.decode('utf-8').strip('\r\n'))  #如果GBK解码失败再尝试UTF-8解码
        else:
            break

printCmd('python ' + file)
printCmd('ping 192.168.1.1')

image.png

回帖
请输入回帖内容 ...