我将Iron
Python(2.6.1)嵌入到C#程序集中,并将几个对象暴露给使用PythonEngine.ExecuteFile执行的脚本.我暴露他们
scope.SetVariable("SomeObject",new SomeObject())
要么
engine.Execute("from MyNamespace import SomeObject",scope)
这取决于脚本如何使用它们.我的应用程序组合被添加到引擎
engine.Runtime.LoadAssembly(Assembly.GetExecutingAssembly())
现在一个脚本可以执行帮助(SomeObject)并且转储漂亮的小帮助信息(*),但是它是不完整的.没有一个对象的事件或属性(当然是公开的)出现,并且许多“内置”成员也丢失.
这是奇怪的部分;如果我启动ipy.exe并执行以下命令:
import sys sys.path.append('<location of my app>') import clr clr.AddReferenceToFile('myapp.exe') from MyNamespace import SomeObject help(SomeObject)
我得到一个不同的转储,完成所有的失踪成员!
为什么两者不同?
奖金问题:假设我正确地工作,是否可以在我的CLR对象上添加描述性文本到help()的输出?就像你可以从脚本中,你的python本机类型?我的第一个猜测是DescriptionAttribute,但是没有工作.
(*)显然,一个最终的工作脚本不会这样做,但是在编写/测试脚本时非常有用.
回答
这是一个完整的控制台程序,说明如何使用标准的python库help()导入替换无内部帮助()的站点.
using System; using System.Collections.Generic; using System.Reflection; using IronPython.Hosting; using IronPython.Runtime; using Microsoft.Scripting.Hosting.Providers; namespace MyApp { class Program { static void Main(string[] args) { // Work around issue w/ pydoc - piping to more doesn't work so instead indicate that we're a dumb terminal if (Environment.GetEnvironmentVariable("TERM") == null) Environment.SetEnvironmentVariable("TERM","dumb"); var engine = Python.CreateEngine(); // Add standard Python library path (is there a better way to do this??) PythonContext context = HostingHelpers.GetLanguageContext(engine) as PythonContext; ICollection<string> paths = context.GetSearchPaths(); paths.Add(@"C:\Program Files (x86)\IronPython 2.6\Lib"); context.SetSearchPaths(paths); // Import site module engine.ImportModule("site"); engine.Runtime.LoadAssembly(Assembly.GetEntryAssembly()); var scope = engine.CreateScope(); scope.SetVariable("SomeObject",new SomeObject()); engine.Execute("help(SomeObject)",scope); } } /// <summary> /// Description of SomeObject. /// </summary> public class SomeObject { /// <summary> /// Description of SomeProperty. /// </summary> public int SomeProperty { get; set; } /// <summary> /// Description of SomeMethod. /// </summary> public void SomeMethod() { } /// <summary> /// Description of SomeEvent. /// </summary> public event EventHandler SomeEvent; } }