python程序执行cmd乱码

背景起源
需要svn log -limit 1获取日志(含中文),
我Python程序运行毫无问题,程序无乱码,中文可以正常解析,
但是有功能需要调用其他程序,调用(客户端)node去做一些事情,
然后莫名其妙的就乱码了,变成了
| 1 line\r\n\r\n1????????????\r\n


解决
知道是编码问题,然后我就开始尝试
utf-8
gbk
ISO-8859-1
以上都不管用
然后gb2312拯救了我,他可以解决大部分乱码
r = svn_call(cmd, stderr=None, cwd=cwd,encoding="gb2312")

其实到这里未真正解决,有的时候还会出现乱码

1.获取svn log日志乱码---------------------------------------------------------------------------------------------------------------------------------------------------------------------

# 2023-12-21 彻底解决

修改管道获取svn log的方法

import json


def svn_log(cwd=None, limit=50):
    """
        取最近的limit条
    """
    try:
        import subprocess
        import xml.etree.ElementTree as ET
        process = subprocess.Popen(["svn", "log", "-l", f"{limit}", "--xml"],cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        output, error = process.communicate()
        # 解码输出为utf-8
        utf8_output = output.decode("utf-8", errors='ignore')
        # 解析 XML 字符串
        tree = ET.fromstring(utf8_output)
        # 遍历每个 logentry
        result = {}
        for logentry in tree.findall('.//logentry'):
            temp_dic = {}
            revision = logentry.get('revision')
            author = logentry.find('author').text
            date = logentry.find('date').text
            msg = logentry.find('msg').text
            temp_dic["author"] = author
            temp_dic["time"] = date
            temp_dic["message"] = msg

            result[revision] = temp_dic

    except Exception as e:
        print(f"取日志报错:\n{e}")

    return result

cwd = "E:\workspace\csjs2\\autobuild"
limit = 2
logs_dic = svn_log(cwd,limit)
logs_str = json.dumps(logs_dic,ensure_ascii=False,indent=4)
print(logs_str)
View Code

效果如下

 

2.SVN提交日志乱码---------------------------------------------------------------------------------------------------------------------------------------------------------------------

# 主要使用以下命令

svn commit -m "中文信息"

 # 解决思路,使用svn commit -F代码如下

def svn_commit(svn_config, path, commit_message, project_workspace):
    import subprocess, os
    username = svn_config["username"]
    password = svn_config["password"]
    try:
        # 创建提交消息文件
        commit_message_dir = os.path.join(project_workspace, "svn_commit_msg")
        if not os.path.exists(commit_message_dir):
            os.makedirs(commit_message_dir)
        commit_file_path = os.path.join(commit_message_dir, "svn_commit_msg.txt")
        with open(commit_file_path, 'w', encoding='utf-8') as commit_file:
            commit_file.write(commit_message)

        # 构建 SVN 提交命令
        svn_command = [
            'svn',
            'commit',
            '--username', username,
            '--password', password,
            '--file', commit_file_path,
            '--encoding', 'utf-8',
            path
        ]

        # 执行 SVN 提交命令
        subprocess.run(svn_command, check=True)

        log.info("SVN提交成功!")

    except subprocess.CalledProcessError as e:
        log.info(f"SVN提交失败。错误信息: {e}")
    except Exception as ex:
        log.info(f"发生未知错误: {ex}")
    finally:
        # 删除提交消息文件
        try:
            # os.remove(commit_file_path)
            pass
        except Exception as ex:
            log.info(f"删除提交消息文件失败: {ex}")
        return '', ''
stdout, stderr = svn_commit(config.svn, out_dir, msg, config.project_workspace)
View Code

 

 
posted @ 2023-03-21 18:19    阅读(45)  评论(0编辑  收藏  举报