当我使用 PythonNet 从 Python 加载 .Net 类时,它不会填充该类的 python __ dict__ ,但是当我使用相同的命令序列从 ipython 加载它时,它会填充该类。谁能说一下如何从普通 Python 获得 ipython 行为?
非常感谢。
python -c "import clr; clr.AddReference('System.Windows.Forms'); import System.Windows.Forms; print len(System.Windows.Forms.__dict__)"
3
ipython -c "import clr; clr.AddReference('System.Windows.Forms'); import System.Windows.Forms; print len(System.Windows.Forms.__dict__)"
714
我已经在 python 2.7.11 和 3.5.2 中尝试过这个。 Pythonnet 2.0.0 和 2.1.0。我相信我正在使用 CLR 4.0.30319(它与其他版本一起安装)。
我认为 ipython 正在做某种内省(introspection)/反射来查找 Forms 类/模块的成员,也许是为了它的完成/智能感知。我如何在常规 Python 中调用它?
这是一个更长的版本,它打印内容(根据 denfromufa 的要求) - 调用文件 TestPN.py:
import clr
clr.AddReference('System.Windows.Forms')
import System.Windows.Forms
nCount = 0
for s, o in System.Windows.Forms.__dict__.items():
print(s, o, type(o))
nCount += 1
if nCount > 10:
break
以及每个的输出:
ipython TestPN.py
SelectionRange <class 'System.Windows.Forms.SelectionRange'> <class 'CLR.CLR Metatype'>
PropertyGrid <class 'System.Windows.Forms.PropertyGrid'> <class 'CLR.CLR Metatype'>
DataGridViewCellStyleConverter <class 'System.Windows.Forms.DataGridViewCellStyleConverter'> <class 'CLR.CLR Metatype'>
PrintPreviewControl <class 'System.Windows.Forms.PrintPreviewControl'> <class 'CLR.CLR Metatype'>
BindingManagerDataErrorEventArgs <class 'System.Windows.Forms.BindingManagerDataErrorEventArgs'> <class 'CLR.CLR Metatype'>
KeyPressEventArgs <class 'System.Windows.Forms.KeyPressEventArgs'> <class 'CLR.CLR Metatype'>
TableLayoutPanelCellPosition <class 'System.Windows.Forms.TableLayoutPanelCellPosition'> <class 'CLR.CLR Metatype'>
TreeViewImageIndexConverter <class 'System.Windows.Forms.TreeViewImageIndexConverter'> <class 'CLR.CLR Metatype'>
DrawListViewSubItemEventArgs <class 'System.Windows.Forms.DrawListViewSubItemEventArgs'> <class 'CLR.CLR Metatype'>
ItemChangedEventArgs <class 'System.Windows.Forms.ItemChangedEventArgs'> <class 'CLR.CLR Metatype'>
ToolStripItemRenderEventArgs <class 'System.Windows.Forms.ToolStripItemRenderEventArgs'> <class 'CLR.CLR Metatype'>
python TestPN.py
__name__ System.Windows.Forms <class 'str'>
__doc__ Namespace containing types from the following assemblies:
- System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
- System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
<class 'str'>
__class__ <class 'CLR.ModuleObject'> <class 'type'>
__file__ C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Drawing\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll <class 'str'>
python --version
Python 3.5.2
ipython --version
5.1.0
最佳答案
答案是使用clr.setPreload(True)
import clr
clr.AddReference('System.Windows.Forms')
clr.setPreload(True)
import System.Windows.Forms
print(len(System.Windows.Forms.__dict__))
输出:
714
...根据需要。
如您所料,import
语句的速度有点慢。
关于PythonNet - 如何填充 __dict__ - ipython 可以,python 没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41388118/