【发布时间】:2014-12-20 15:35:02
【问题描述】:
我正在尝试将包含文件路径的变量从我的 C# 应用程序传递到我的 Python 脚本中的 temp.xml 文件,但我不断收到 Illegal Characters in Path 异常。我觉得我已经完成了 Stackoverflow 上提到的几乎所有事情,以修复 C# 端和 Python 端的非法字符/路径,但似乎没有任何效果。我该如何克服这个障碍!?
这是我用来打开/替换坏字符并将temp.xml写入C:\Temp\目录的C#代码:
StreamReader sr1 = new StreamReader(filePath);
string tempFile = @"C:\Temp\temp.xml";
File.Copy(filePath, tempFile, true);
StreamWriter sw = new StreamWriter(tempFile);
sw.AutoFlush = true;
string xml = sr1.ReadToEnd();
string regExp = @"</(\w+)>";
MatchCollection mc = Regex.Matches(xml, regExp);
foreach (Match m in mc)
{
string val = m.Groups[1].Value;
string regExp2 = "<" + val + "( |>)";
Match m2 = Regex.Match(xml, regExp2);
if (m2.Success)
{
char[] chars = xml.ToCharArray();
chars[m2.Index] = '~';
xml = new string(chars);
xml = Regex.Replace(xml, @"</" + val + ">", "~/" + val + ">");
}
xml = Regex.Replace(xml, @"<\?", @"~?"); // declarations
xml = Regex.Replace(xml, @"<!", @"~!"); // comments
}
string regExp3 = @"<\w+\s?/>";
Match m3 = Regex.Match(xml, regExp3);
if (m3.Success)
{
char[] chars = xml.ToCharArray();
chars[m3.Index] = '~';
xml = new string(chars);
}
xml = Regex.Replace(xml, ">|->", ">");
xml = Regex.Replace(xml, "<", "<");
xml = Regex.Replace(xml, "~", "<");
xml = Regex.Replace(xml, "&", "&");
xml = Regex.Replace(xml, "“|”", "\"");
xml = Regex.Replace(xml, "’", "'");
xml = Regex.Replace(xml, "‘", "\"");
xml = Regex.Replace(xml, "–", "-");
sw.WriteLine(xml);
sw.Close();
ScriptEngine engine = Python.CreateEngine();
ScriptScope scope = engine.CreateScope();
var paths = engine.GetSearchPaths();
paths.Add(@"C:\Program Files (x86)\IronPython 2.7\Lib");
engine.SetSearchPaths(paths);
var parameters = new Dictionary<string, object>()
{
{"scapFilePath", tempFile}, {"scapProfile", profile}
};
scope = engine.CreateScope(parameters);
//EXCEPTION IS THROWN HERE
try
{
dynamic result = engine.ExecuteFile("xccdf-xml2tsv.py", scope);
}
catch (Exception e)
{
Messagebox.Show(e.toString());
}
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
这是我在 python 脚本中处理上面定义的 scope 变量的代码:
import csv
import sys
import os
import traceback
reload(sys)
sys.setdefaultencoding('utf-8')
import xml.etree.ElementTree as ET
xmlns = "http://checklists.nist.gov/xccdf/1.1"
scapFile = os.path.normpath(scapFilePath)
try:
xml = ET.parse(scapFile)
except Exception,e:
traceback.print_exc()
sys.exit(-1)
这是我当前的scope 变量在异常发生时:
这是一个例外:
感谢任何帮助;我已经坚持了两天了!!
【问题讨论】:
-
您在哪个平台(操作系统与版本)中运行程序?如果我没记错的话 - 在你的文件名中可能会导致问题。
-
我在 Windows 8、Visual Studio 12、Ironpython 2.7 中运行它,当我使用 Windows 7 运行时,问题是相同的。
标签: c# python ironpython filepath