`str.format()`

时间:2016-08-17 21:21:45

标签: python unicode encoding python-unicode

我正在尝试运行以下脚本,该脚本扫描*.csproj文件并检查Visual Studio解决方案中的项目依赖项,但是我收到以下错误。我已经尝试了各种codecencode/decode以及u''组合,但无济于事......

(变音符号意图,我打算保留它们。)

Traceback (most recent call last):   
  File "E:\00 GIT\SolutionDependencies.py", line 44, in <module>
    references = GetProjectReferences("MiotecGit")
  File "E:\00 GIT\SolutionDependencies.py", line 40, in GetProjectReferences
    outputline = u'"{}" -> "{}"'.format(projectName, referenceName)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 19: ordinal not in range(128)
import glob
import os
import fnmatch
import re
import subprocess
import codecs

gvtemplate = """
digraph g {

rankdir = "LR"

#####

}
""".strip()

def GetProjectFiles(rootFolder):
    result = []
    for root, dirnames, filenames in os.walk(rootFolder):
        for filename in fnmatch.filter(filenames, "*.csproj"):
            result.append(os.path.join(root, filename))
    return result

def GetProjectName(path):
    result = os.path.splitext(os.path.basename(path))[0]
    return result

def GetProjectReferences(rootFolder):
    result = []
    projectFiles = GetProjectFiles(rootFolder)
    for projectFile in projectFiles:
        projectName = GetProjectName(projectFile)
        with codecs.open(projectFile, 'r', "utf-8") as pfile:
            content = pfile.read()
            references = re.findall("<ProjectReference.*?</ProjectReference>", content, re.DOTALL)
            for reference in references:
                referenceProject = re.search('"([^"]*?)"', reference).group(1)
                referenceName = GetProjectName(referenceProject)
                outputline = u'"{}" -> "{}"'.format(projectName, referenceName)
                result.append(outputline)
    return result

references = GetProjectReferences("MiotecGit")

output = u"\n".join(*references)

with codecs.open("output.gv", "w", 'utf-8') as outputfile:
    outputfile.write(gvtemplate.replace("#####", output))


graphvizpath = glob.glob(r"C:\Program Files*\Graphviz*\bin\dot.*")[0]
command = '{} -Gcharset=latin1 -T pdf -o "output.pdf" "output.gv"'.format(graphvizpath)
subprocess.call(command)

1 个答案:

答案 0 :(得分:1)

当Python 2.x尝试在Unicode上下文中使用字节字符串时,它会使用decode编解码器自动尝试将字节字符串ascii转换为Unicode字符串。虽然ascii编解码器是一种安全的选择,但它通常无法正常工作。

对于Windows环境,mbcs编解码器将选择Windows用于8位字符的代码页。您可以明确地自己解码字符串。

outputline = u'"{}" -> "{}"'.format(projectName.decode('mbcs'), referenceName.decode('mbcs'))