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 @ 2024-01-30 16:13  乐swap火  阅读(71)  评论(0编辑  收藏  举报