我試圖運行以下腳本,它掃描*.csproj
文件並檢查Visual Studio解決方案中的項目依賴關係,但出現以下錯誤。我已經試過各種codec
和encode/decode
和u''
組合,都無濟於事......`str.format()`中的Unicode錯誤
(變音符號被打算,我打算讓他們)。
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)
不能用正則表達式解析XML文件。使用xml解析器(如'ElementTree')。 – Daniel
請用全小寫名稱命名您的函數,以便語法突出顯示不會將它們格式化爲類名稱。 –
@Daniel我不解析,我在尋找。但我明白了,謝謝你的建議!如果我真的最終使用腳本,就像我想的那樣,這將是值得的額外工作。 – heltonbiker