python-import - Instantiate a .Net class from IronPython without boilerplate
问题描述
To use a class from the .Net host application in IronPython, you can do this:
import clr
clr.AddReference('MyApplication')
from MyApplication import MyClass
x = MyClass()
But how can I do it without the first 3 lines or perhaps somehow executing them in the host application before it runs the script?
解决方案
在Microsoft.Scripting.Hosting
(这是 IronPython 中使用的动态语言运行时的一部分)中,您有一个ScriptScope的概念,您可以在其上执行语句或源脚本。
这允许您在执行实际脚本之前在范围上执行样板。以下示例显示了基本思想:
var engine = Python.CreateEngine();
var scope = engine.CreateScope();
var boilerplateSourceText = @"import clr
clr.AddReference('MyApplication')
from MyApplication import MyClass
";
var boilerplateSource = engine.CreateScriptSourceFromString(boilerplateSourceText, SourceCodeKind.Statements);
boilerplateSource.Execute(scope);
var scriptSource = engine.CreateScriptSourceFromString("x = MyClass()", SourceCodeKind.Statements);
scriptSource.Execute(scope);
推荐阅读
- reactjs - 用于分页的 Ag-grid 和句柄
- hololens - 是否可以通过 intune 在 hololens 2 上推送自定义文件?
- docker - 无法手动将 ssl certfile 安装到托管在 docker 容器中的 .app 域
- python - 使用条件循环并删除python中的特定行
- r - 在为多个搜索字符串搜索多个列时如何使用str_detect
- kubernetes - Pod 拥有比预期更多的资源
- python - discord.py on member join ,给出角色命令
- python - 在 on_member_join 事件中添加 ctx
- postgresql - PostgreSQL COPY 附加页眉 - csv 中的页脚行
- mongodb - 如何将字符串附加到 MOngoDB robo3T 中的数组