如何在IronPython中引用已编译的Python代码?
我们需要在C#中引用.py代码。这个问题通过使用IronPython 2.6解决了。
问题出在.py代码中使用了'import customlib',而这个库是编译成customlib.pyc的。
IronPython报错:IronPython.Runtime.Exceptions.ImportException: 没有名为customlib的模块。
尝试的解决方案:
在Python代码中这样添加引用:
import sys
sys.path.append('c:\path to customlib')
这对其他.py文件似乎有效,但对.pyc文件不行。
问题:
1) 如何在IronPython中引用.pyc?
2) 如果不可能,有什么替代方案可以在C#.Net中使用.py和.pyc?
(显然我们没有customlib.pyc的.py源代码)
适用于.py但不适用于.py导入.pyc的C#代码:
ScriptEngine engine = Python.CreateEngine();
ScriptScope pyScope = null;
ScriptSource ss = null;
...
pyScope = engine.CreateScope();
ss = engine.CreateScriptSourceFromFile(@"C:\test.py");
ss.Execute(pyScope);
...
int result = (int)engine.Operations.InvokeMember(pyScope, "funcName")
谢谢!
1 个回答
2
*.pyc
文件是专门为 CPython 设计的。你需要将它们反编译或者使用 CPython 来运行。
如果你想反编译,可以试试: