windows上使用python2.7获取svn info,中文路径乱码问题

复制代码
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import subprocess
import cmd
import os

os.environ['LANG'] = 'en_US.UTF-8'

class SVNCommand(cmd.Cmd):
    def do_svninfo(self, folder_path):
        # 构建svn info命令
        command = ['svn', 'info', folder_path]
        print(command)
        try:
            # 转换命令字符串为本地编码
            if isinstance(command, list):
                command = [c.encode(sys.getfilesystemencoding()) for c in command]
            else:
                command = command.encode(sys.getfilesystemencoding())
            
            # 运行svn info命令并捕获输出
            process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
            
            output, error = process.communicate()

            if error:
                print("Error executing SVN command:")
                # print(error.decode(sys.getfilesystemencoding())) # 在这里改成.decode(sys.getfilesystemencoding())
                print(error)
                return

            print(output.decode('utf-8'))

        except subprocess.CalledProcessError as e:
            # 如果命令运行错误,则将错误信息打印出来
            print("Error executing SVN command:")
            print(e.output.decode('utf-8'))

    def default(self, line):
        print("Unknown command:", line)

if __name__ == '__main__':
    folder_path = u"F:\\workDoc\\Doc\\我的文档"
    SVNCommand().do_svninfo(folder_path)
复制代码

encode方法用于将str类型的字符串转换为bytes类型的二进制数据,这个过程也称为“编码”。

decode方法用于将bytes类型的二进制数据转换为str类型的字符串,这个过程也称为“解码”。

其中最重要就是使用sys.getfilesystemencoding ()函数获取文件系统使用的编码方式,这个函数会根据操作系统的不同返回不同的值

# 转换命令字符串为本地编码
if isinstance(command, list):
command = [c.encode(sys.getfilesystemencoding()) for c in command]
else:
command = command.encode(sys.getfilesystemencoding())

 

posted @   乐swap火  阅读(136)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示