Unicode错误`str.格式()`

2024-10-01 15:46:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试运行以下脚本,该脚本扫描*.csproj文件并检查VisualStudio解决方案中的项目依赖项,但我得到以下错误。我已经尝试过各种codecencode/decode和{}的组合,但都没用。。。在

(变音符号是有意的,我打算保留它们)。在

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)

Tags: pathinimportreformatforoutputos
1条回答
网友
1楼 · 发布于 2024-10-01 15:46:43

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

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

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

相关问题 更多 >

    热门问题