X Tutup
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python for .NET\n", "\n", "Python for .NET (`pythonnet`, `Python.NET`) is a package that gives Python programmers\n", "nearly seamless integration with the .NET 4.0+ Common Language Runtime\n", "(CLR) on Windows and Mono runtime on Linux and OSX. Python for .NET\n", "provides a powerful application scripting tool for .NET developers.\n", "Using this package you can script .NET applications or build entire\n", "applications in Python, using .NET services and components written in\n", "any language that targets the CLR (C#, VB.NET, F#, C++/CLI).\n", "\n", "Note that this package does _not_ implement Python as a first-class CLR\n", "language - it does not produce managed code (IL) from Python code. Rather,\n", "it is an integration of the CPython engine with the .NET or Mono runtime.\n", "This approach allows you to use CLR services and continue to use existing\n", "Python code and C-API extensions while maintaining native execution\n", "speeds for Python code. If you are interested in a pure managed-code\n", "implementation of the Python language, you should check out the\n", "[IronPython][1] project, which is in active development.\n", "\n", "Python for .NET is currently compatible and tested with Python releases\n", "`2.7`, `3.3`, `3.4`, `3.5`, and `3.6`.\n", "Current releases are available at the [Python for .NET website][2].\n", "To subscribe to the [Python for .NET mailing list][3] or read the\n", "[online archives][4] of the list, see the [mailing list information][3]\n", "page. Use the [Python for .NET issue tracker][55] to report issues.\n", "\n", "- The document provides a detailed overview of Python for .NET,\n", " as well as some basic usage examples. Many other examples can be\n", " found in the demos and unit tests for the package.\n", "- Checkout the [`Python.NET`][77] code from github.\n", "- [Download releases][6] for various versions of Python and CLR.\n", "\n", "[1]: http://www.ironpython.com\n", "\n", "[2]: http://pythonnet.github.io/\n", "\n", "[3]: http://mail.python.org/mailman/listinfo/pythondotnet\n", "\n", "[4]: http://mail.python.org/pipermail/pythondotnet/\n", "\n", "[5]: https://github.com/pythonnet/pythonnet/releases\n", "\n", "[6]: https://pypi.python.org/pypi/pythonnet\n", "\n", "[7]: http://www.go-mono.com\n", "\n", "[8]: https://github.com/pythonnet/pythonnet/blob/master/README.md\n", "\n", "[9]: http://pythonnet.github.io/LICENSE\n", "\n", "[10]: http://www.python.org/license.html\n", "\n", "[55]: http://github.com/pythonnet/pythonnet/issues\n", "\n", "[66]: http://pythonnet.github.io/readme.html\n", "\n", "[77]: http://github.com/pythonnet/pythonnet" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Installation\n", "\n", "Python for .NET is available as a source release on [GitHub][5] and as a\n", "binary wheel distribution for all supported versions of Python and the\n", "common language runtime from the [Python Package Index][6].\n", "\n", "The source release is a self-contained \"private\" assembly. Just unzip the\n", "package wherever you want it, cd to that directory, build the solution\n", "`python setup.py build_ext --inplace`. Once you start up Python or\n", "IPython interpreter in this directory or append this directory to\n", "`sys.path`, then after `import clr` statement .NET assemblies can\n", "be used.\n", "You can also run `nPython.exe` (`mono nPython.exe` on `*nix`) to check\n", "how python can be embedded in console .NET application. Note that the\n", "source release does not include a copy of the CPython runtime, so you will\n", "need to have installed Python on your machine before using the source release.\n", "\n", "**Running on Linux/Mono:** Unit testing shows that `Python.NET` will run\n", "under [Mono][7], though the Mono runtime is less supported so there still\n", "may be problems.\n", "\n", "\n", "\n", "[5]: https://github.com/pythonnet/pythonnet/releases\n", "\n", "[6]: https://pypi.python.org/pypi/pythonnet\n", "\n", "[7]: http://www.go-mono.com\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Getting Started\n", "\n", "A key goal for this project has been that Python for .NET should\n", "\"work just the way you'd expect in Python\", except for cases that are\n", ".NET specific (in which case the goal is to work \"just the way\n", "you'd expect in C#\"). In addition, with the IronPython project having\n", "established a community, it is my goal that code written for IronPython\n", "run without modification under Python for .NET.\n", "\n", "If you already know Python, you can probably finish this readme and then\n", "refer to .NET docs to figure out anything you need to do. Conversely if\n", "you are familiar with C# or another .NET language, you probably just need\n", "to pick up one of the many good Python books or read the Python tutorial\n", "online to get started.\n", "\n", "A good way to start is to interactively explore .NET usage in python\n", "interpreter by following along with the examples in this document. If you\n", "get stuck, there are also a number of demos and unit tests located in the\n", "source directory of the distribution that can be helpful as examples." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Importing Modules\n", "\n", "Python for .NET allows CLR namespaces to be treated essentially as\n", "Python packages." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import clr\n", "from System import String\n", "clr.AddReference('System.Collections')\n", "from System.Collections import *" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Types from any loaded assembly may be imported and used in this manner.\n", "To load an assembly, use the `AddReference` function in the `clr` module:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "clr.AddReference(\"System.Windows.Forms\")\n", "from System.Windows.Forms import Form" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Note** Earlier releases of Python for .NET relied on \"implicit loading\"\n", "to support automatic loading of assemblies whose names corresponded to an\n", "imported namespace. Implicit loading still works for backward compatibility,\n", "but will be removed in a future release so it is recommended to use\n", "the `clr.AddReference` method.\n", "\n", "Python for .NET uses the PYTHONPATH (sys.path) to look for assemblies\n", "to load, in addition to the usual application base and the GAC. To ensure\n", "that you can implicitly import an assembly, put the directory containing\n", "the assembly in `sys.path`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using Classes\n", "\n", "Python for .NET allows you to use any non-private classes, structs,\n", "interfaces, enums or delegates from Python. To create an instance of a\n", "managed class, you use the standard instantiation syntax, passing a set\n", "of arguments that match one of its public constructors:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from System.Drawing import Point\n", "\n", "p = Point(5, 5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In most cases, Python for .NET can determine the correct constructor to\n", "call automatically based on the arguments. In some cases, it may be necessary\n", "to call a particular overloaded constructor, which is supported by a special\n", "`__overloads__` attribute, which will soon be deprecated in favor of\n", "iPy compatible \"Overloads\", on a class:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "from System import String, Char, Int32\n", "\n", "s = String.Overloads[Char, Int32]('A', 10)\n", "s = String.Overloads[Char, Int32]('A', 10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using Generics\n", "\n", "`Python.NET` also supports generic types. A generic type must be bound to\n", "create a concrete type before it can be instantiated. Generic types support\n", "the subscript syntax to create bound types:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from System.Collections.Generic import Dictionary\n", "from System import *\n", "\n", "dict1 = Dictionary[String, String]()\n", "dict2 = Dictionary[String, Int32]()\n", "dict3 = Dictionary[String, Type]()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When you pass a list of types using the subscript syntax, you can also\n", "pass a subset of Python types that directly correspond to .NET types:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": true }, "outputs": [], "source": [ "dict1 = Dictionary[str, str]()\n", "dict2 = Dictionary[str, int]()\n", "dict3 = Dictionary[str, Decimal]()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This shorthand also works when explicitly selecting generic methods or\n", "specific versions of overloaded methods and constructors (explained later).\n", "\n", "You can also subclass managed classes in Python, though members of the\n", "Python subclass are not visible to .NET code. See the `helloform.py` file\n", "in the `/demo` directory of the distribution for a simple Windows Forms\n", "example that demonstrates subclassing a managed class." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Fields And Properties\n", "\n", "You can get and set fields and properties of CLR objects just as if they\n", "were regular attributes:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from System import Environment\n", "\n", "name = Environment.MachineName\n", "Environment.ExitCode = 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using Indexers\n", "\n", "If a managed object implements one or more indexers, you can call the\n", "indexer using standard Python indexing syntax:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from System.Collections import Hashtable\n", "\n", "table = Hashtable()\n", "table[\"key 1\"] = \"value 1\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Overloaded indexers are supported, using the same notation one would\n", "use in C#:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": true }, "outputs": [], "source": [ "#Loading clrmagic extension (pip install clrmagic) to generate runtime C# code, usable from IPython\n", "%reload_ext clrmagic" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Below is runtime generated method `idxnames` that shows example of overloading indexer in CLR type `IndexedNames`" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ ".>" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%CS idxnames System.dll\n", "static IndexedNames idxn;\n", "public static object idxnames()\n", "{\n", " if (idxn == null) idxn = new IndexedNames();\n", " return idxn;\n", "}\n", "class IndexedNames\n", "{\n", " private string[] namelist = new string[size];\n", " static public int size = 10;\n", " public IndexedNames()\n", " {\n", " for (int i = 0; i < size; i++)\n", " {\n", " namelist[i] = \"N. A.\";\n", " }\n", " }\n", "\n", " public string this[int index]\n", " {\n", " get\n", " {\n", " string tmp;\n", "\n", " if( index >= 0 && index <= size-1 )\n", " {\n", " tmp = namelist[index];\n", " }\n", " else\n", " {\n", " tmp = \"\";\n", " }\n", "\n", " return ( tmp );\n", " }\n", " set\n", " {\n", " if( index >= 0 && index <= size-1 )\n", " {\n", " namelist[index] = value;\n", " }\n", " }\n", " }\n", " public int this[string name]\n", " {\n", " get\n", " {\n", " int index = 0;\n", " while(index < size)\n", " {\n", " if (namelist[index] == name)\n", " {\n", " return index;\n", " }\n", " index++;\n", " }\n", " return index;\n", " }\n", "\n", " }\n", "}" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(5, 'abc', 'N. A.')" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "idx1=idxnames()\n", "\n", "idx1[5]=\"abc\"\n", "\n", "idx1[\"abc\"], idx1[5], idx1[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using Methods\n", "\n", "Methods of CLR objects behave generally like normal Python methods.\n", "Static methods may be called either through the class or through an\n", "instance of the class. All public and protected methods of CLR objects\n", "are accessible to Python:" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['C:\\\\', 'D:\\\\']" ] }, "execution_count": 47, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from System import Environment\n", "\n", "drives = Environment.GetLogicalDrives()\n", "list(drives)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It is also possible to call managed methods `unbound`\n", "(passing the instance as the first argument) just as with Python methods.\n", "This is most often used to explicitly call methods of a base class.\n", "\n", "**Note** There is one caveat related to calling unbound methods: it is\n", "possible for a managed class to declare a static method and an instance\n", "method with the same name. Since it is not possible for the runtime to know\n", "the intent when such a method is called unbound, the static method will\n", "always be called.\n", "\n", "The docstring of CLR a method (**doc**) can be used to view the signature\n", "of the method, including overloads if the CLR method is overloaded.\n", "You can also use the Python `help` method to inspect a managed class:" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "System.String GetFolderPath(SpecialFolder)\r\n", "System.String GetFolderPath(SpecialFolder, SpecialFolderOption)\n", "Help on class Environment in module System:\n", "\n", "class Environment(Object)\n", " | Void .ctor()\n", " | \n", " | Method resolution order:\n", " | Environment\n", " | Object\n", " | builtins.object\n", " | \n", " | Methods defined here:\n", " | \n", " | __call__(self, /, *args, **kwargs)\n", " | Call self as a function.\n", " | \n", " | __delitem__(self, key, /)\n", " | Delete self[key].\n", " | \n", " | __eq__(self, value, /)\n", " | Return self==value.\n", " | \n", " | __ge__(self, value, /)\n", " | Return self>=value.\n", " | \n", " | __getitem__(self, key, /)\n", " | Return self[key].\n", " | \n", " | __gt__(self, value, /)\n", " | Return self>value.\n", " | \n", " | __hash__(self, /)\n", " | Return hash(self).\n", " | \n", " | __init__(self, /, *args, **kwargs)\n", " | Initialize self. See help(type(self)) for accurate signature.\n", " | \n", " | __iter__(self, /)\n", " | Implement iter(self).\n", " | \n", " | __le__(self, value, /)\n", " | Return self<=value.\n", " | \n", " | __lt__(self, value, /)\n", " | Return self\n", " | Void Exit(Int32)\n", " | \n", " | ExitCode = 1\n", " | \n", " | ExpandEnvironmentVariables = \n", " | Void FailFast(System.String)\r\n", " | Void FailFast(System.String, System.Exception)\n", " | \n", " | GetCommandLineArgs = \n", " | System.String[] GetCommandLineArgs()\n", " | \n", " | GetEnvironmentVariable = \n", " | System.String GetEnvironmentVariable(System.String)\r\n", " | System.String GetEnvironmentVariable(System.String, System.EnvironmentVariableTarget)\n", " | \n", " | GetEnvironmentVariables = \n", " | System.Collections.IDictionary GetEnvironmentVariables()\r\n", " | System.Collections.IDictionary GetEnvironmentVariables(System.EnvironmentVariableTarget)\n", " | \n", " | GetFolderPath = \n", " | System.String GetFolderPath(SpecialFolder)\r\n", " | System.String GetFolderPath(SpecialFolder, SpecialFolderOption)\n", " | \n", " | GetLogicalDrives = \n", " | System.String[] GetLogicalDrives()\n", " | \n", " | HasShutdownStarted = False\n", " | \n", " | Is64BitOperatingSystem = True\n", " | \n", " | Is64BitProcess = True\n", " | \n", " | MachineName = 'DESKTOP-SOAE0FK'\n", " | \n", " | NewLine = '\\r\\n'\n", " | \n", " | OSVersion = \n", " | Void .ctor(System.PlatformID, System.Version)\n", " | \n", " | ProcessorCount = 4\n", " | \n", " | SetEnvironmentVariable = \n", " | Void SetEnvironmentVariable(System.String, System.String)\r\n", " | Void SetEnvironmentVariable(System.String, System.String, System.EnvironmentVariableTarget)\n", " | \n", " | SpecialFolder = \n", " | Void .ctor()\n", " | \n", " | SpecialFolderOption = \n", " | Void .ctor()\n", " | \n", " | StackTrace = r' at System.Environment.GetStackTrace(Exception...s\\py...\n", " | \n", " | SystemDirectory = r'C:\\WINDOWS\\system32'\n", " | \n", " | SystemPageSize = 4096\n", " | \n", " | TickCount = 7540656\n", " | \n", " | UserDomainName = 'DESKTOP-SOAE0FK'\n", " | \n", " | UserInteractive = True\n", " | \n", " | UserName = 'denis'\n", " | \n", " | Version = \n", " | Void .ctor()\r\n", " | Void .ctor(Int32, Int32)\r\n", " | Void .ctor(System.String)\r\n", " | Void .ctor(Int32, Int32, Int32)\r\n", " | Void .ctor(Int32, Int32, Int32, Int32)\n", " | \n", " | WorkingSet = 143998976\n", " | \n", " | get_CommandLine = \n", " | System.String get_CommandLine()\n", " | \n", " | get_CurrentDirectory = \n", " | System.String get_CurrentDirectory()\n", " | \n", " | get_CurrentManagedThreadId = \n", " | Int32 get_ExitCode()\n", " | \n", " | get_HasShutdownStarted = \n", " | Boolean get_HasShutdownStarted()\n", " | \n", " | get_Is64BitOperatingSystem = \n", " | Boolean get_Is64BitProcess()\n", " | \n", " | get_MachineName = \n", " | System.String get_MachineName()\n", " | \n", " | get_NewLine = \n", " | System.String get_NewLine()\n", " | \n", " | get_OSVersion = \n", " | System.OperatingSystem get_OSVersion()\n", " | \n", " | get_ProcessorCount = \n", " | Int32 get_ProcessorCount()\n", " | \n", " | get_StackTrace = \n", " | System.String get_StackTrace()\n", " | \n", " | get_SystemDirectory = \n", " | System.String get_SystemDirectory()\n", " | \n", " | get_SystemPageSize = \n", " | Int32 get_SystemPageSize()\n", " | \n", " | get_TickCount = \n", " | Int32 get_TickCount()\n", " | \n", " | get_UserDomainName = \n", " | System.String get_UserDomainName()\n", " | \n", " | get_UserInteractive = \n", " | Boolean get_UserInteractive()\n", " | \n", " | get_UserName = \n", " | System.String get_UserName()\n", " | \n", " | get_Version = \n", " | System.Version get_Version()\n", " | \n", " | get_WorkingSet = \n", " | Int64 get_WorkingSet()\n", " | \n", " | set_CurrentDirectory = \n", " | Void set_CurrentDirectory(System.String)\n", " | \n", " | set_ExitCode = \n", " | Void set_ExitCode(Int32)\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data descriptors inherited from Object:\n", " | \n", " | Overloads\n", " | \n", " | __overloads__\n", " | \n", " | ----------------------------------------------------------------------\n", " | Data and other attributes inherited from Object:\n", " | \n", " | Equals = \n", " | Boolean Equals(System.Object)\r\n", " | Boolean Equals(System.Object, System.Object)\n", " | \n", " | Finalize = \n", " | Void Finalize()\n", " | \n", " | GetHashCode = \n", " | Int32 GetHashCode()\n", " | \n", " | GetType = \n", " | System.Type GetType()\n", " | \n", " | MemberwiseClone = \n", " | System.Object MemberwiseClone()\n", " | \n", " | ReferenceEquals = \n", " | Boolean ReferenceEquals(System.Object, System.Object)\n", " | \n", " | ToString = \n", " | System.String ToString()\n", "\n" ] } ], "source": [ "from System import Environment\n", "\n", "print(Environment.GetFolderPath.__doc__)\n", "\n", "help(Environment)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Overloaded and Generic Methods\n", "\n", "While Python for .NET will generally be able to figure out the right\n", "version of an overloaded method to call automatically, there are cases\n", "where it is desirable to select a particular method overload explicitly.\n", "\n", "Methods of CLR objects have an `__overloads__`, which will soon be\n", "deprecated in favor of iPy compatible Overloads, attribute that can be\n", "used for this purpose:" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [], "source": [ "from System import Console\n", "\n", "# in jupyter writes to nbserver console\n", "Console.WriteLine.Overloads[bool](True) \n", "Console.WriteLine.Overloads[str](\"true\")\n", "Console.WriteLine.Overloads[int](42)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Similarly, generic methods may be bound at runtime using the subscript\n", "syntax directly on the method:" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "data": { "text/plain": [ ".>" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "%%CS GenericMethods System.dll\n", "static TypeWithGenerics twg;\n", "\n", "public static object GenericMethods()\n", "{\n", " if (twg == null) twg = new TypeWithGenerics();\n", " return twg;\n", "}\n", "\n", "class TypeWithGenerics\n", "{\n", " public TypeWithGenerics()\n", " {\n", " \n", " }\n", "\n", " public System.Type genericmethod(T g)\n", " {\n", " return g.GetType();\n", " }\n", "}" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('Int32', 'String')" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "twg = GenericMethods()\n", "\n", "twg.genericmethod[int](10).Name, twg.genericmethod[str](\"10\").Name" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Delegates And Events\n", "\n", "Delegates defined in managed code can be implemented in Python.\n", "A delegate type can be instantiated and passed a callable Python object\n", "to get a delegate instance. The resulting delegate instance is a true\n", "managed delegate that will invoke the given Python callable when it\n", "is called:" ] }, { "cell_type": "code", "execution_count": 78, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def my_handler(source, args):\n", " print('my_handler called!')\n", "\n", "# instantiate a delegate\n", "d = AssemblyLoadEventHandler(my_handler)\n", "\n", "# use it as an event handler\n", "AppDomain.CurrentDomain.AssemblyLoad += d\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Multicast delegates can be implemented by adding more callable objects to\n", "a delegate instance:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```python\n", "class test(object):\n", " def method1():\n", " return \"method1\"\n", " def method2():\n", " return \"method2\"\n", "t=test()\n", "d += t.method1\n", "d += t.method2\n", "d()\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Events are treated as first-class objects in Python, and behave in many\n", "ways like methods. Python callbacks can be registered with event attributes,\n", "and an event can be called to fire the event.\n", "\n", "Note that events support a convenience spelling similar to that used in C#.\n", "You do not need to pass an explicitly instantiated delegate instance to an\n", "event (though you can if you want). Events support the `+=` and `-=`\n", "operators in a way very similar to the C# idiom:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```python\n", "def handler(source, args):\n", " print('my_handler called!')\n", "\n", "# register event handler\n", "object.SomeEvent += handler\n", "\n", "# unregister event handler\n", "object.SomeEvent -= handler\n", "\n", "# fire the event\n", "result = object.SomeEvent(...)\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exception Handling\n", "\n", "You can raise and catch managed exceptions just the same as you would\n", "pure-Python exceptions:" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "aiieee!\n", "None\n" ] } ], "source": [ "from System import NullReferenceException\n", "\n", "try:\n", " raise NullReferenceException(\"aiieee!\")\n", "except NullReferenceException as e:\n", " print(e.Message)\n", " print(e.Source)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using Arrays\n", "\n", "The type `System.Array` supports the subscript syntax in order to\n", "make it easy to create managed arrays from Python:" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 2]" ] }, "execution_count": 88, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from System import Array\n", "\n", "#This is regression - TypeError: Cannot convert 10 to System.Int32[]\n", "#myarray = Array[int](10)\n", "\n", "myarray = Array[int]([1,2])\n", "list(myarray)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Managed arrays support the standard Python sequence protocols:" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "2\n", "True\n" ] } ], "source": [ "items = Array[int]([1,2])\n", "\n", "# Get first item\n", "v = items[0]\n", "items[0] = v\n", "print(v)\n", "\n", "# Get last item\n", "v = items[-1]\n", "items[-1] = v\n", "print(v)\n", "\n", "# Get length\n", "l = len(items)\n", "print(l)\n", "\n", "# Containment test\n", "test = v in items\n", "print(test)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Multidimensional arrays support indexing using the same notation one\n", "would use in C#:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```python\n", "items[0, 2]\n", "\n", "items[0, 2, 3]\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using Collections\n", "\n", "Managed arrays and managed objects that implement the IEnumerable\n", "interface can be iterated over using the standard iteration\n", "Python idioms:" ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\n", "clrmodule, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null\n", "Python.Runtime, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null\n", "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\n", "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\n", "__CodeGenerator_Assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n", "e__NativeCall_Assembly, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n", "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\n", "System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\n", "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\n", "System.Data.SqlXml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\n", "System.Collections, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\n", "System.Windows, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\n", "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\n", "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\n", "Accessibility, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\n", "clrmagic, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n", "wfajovyt, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n", "qdqlzr1m, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n", "kdmoukgy, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n", "52yiyr0m, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n", "14zh1gpy, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\n" ] } ], "source": [ "import System\n", "domain = System.AppDomain.CurrentDomain\n", "\n", "for item in domain.GetAssemblies():\n", " name = item.GetName()\n", " print(name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Using COM Components\n", "\n", "Using Microsoft-provided tools such as `aximp.exe` and `tlbimp.exe`,\n", "it is possible to generate managed wrappers for COM libraries. After\n", "generating such a wrapper, you can use the libraries from Python just\n", "like any other managed code.\n", "\n", "Note: currently you need to put the generated wrappers in the GAC, in\n", "the `Python.NET` assembly directory or on the PYTHONPATH in order to load them." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Type Conversion\n", "\n", "Type conversion under Python for .NET is fairly straightforward - most\n", "elemental Python types (string, int, long, etc.) convert automatically to\n", "compatible managed equivalents (String, Int32, etc.) and vice-versa.\n", "Note that all strings returned from the CLR are returned as unicode.\n", "\n", "Types that do not have a logical equivalent in Python are exposed as\n", "instances of managed classes or structs (System.Decimal is an example).\n", "\n", "The .NET architecture makes a distinction between `value types` and\n", "`reference types`. Reference types are allocated on the heap, and value\n", "types are allocated either on the stack or in-line within an object.\n", "\n", "A process called `boxing` is used in .NET to allow code to treat a value\n", "type as if it were a reference type. Boxing causes a separate copy of the\n", "value type object to be created on the heap, which then has reference\n", "type semantics.\n", "\n", "Understanding boxing and the distinction between value types and reference\n", "types can be important when using Python for .NET because the Python\n", "language has no value type semantics or syntax - in Python\n", "\"everything is a reference\".\n", "\n", "Here is a simple example that demonstrates an issue. If you are an\n", "experienced C# programmer, you might write the following code:" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 97, "metadata": {}, "output_type": "execute_result" } ], "source": [ "items = System.Array.CreateInstance(Point, 3)\n", "for i in range(3):\n", " items[i] = Point(0, 0)\n", "\n", "items[0].X = 1 # won't work!!\n", "\n", "items[0].X" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "While the spelling of `items[0].X = 1` is the same in C# and Python,\n", "there is an important and subtle semantic difference.\n", "In C# (and other compiled-to-IL languages), the compiler knows that\n", "Point is a value type and can do the Right Thing here, changing the\n", "value in place.\n", "\n", "In Python however, \"everything's a reference\", and there is really no\n", "spelling or semantic to allow it to do the right thing dynamically.\n", "The specific reason that `items[0]` itself doesn't change is that when\n", "you say `items[0]`, that getitem operation creates a Python object that\n", "holds a reference to the object at `items[0]` via a GCHandle.\n", "That causes a ValueType (like Point) to be boxed, so the following\n", "setattr (`.X = 1`) _changes the state of the boxed value,\n", "not the original unboxed value_.\n", "\n", "The rule in Python is essentially:\n", "\n", "> the result of any attribute or item access is a boxed value\n", "\n", "and that can be important in how you approach your code.\n", "\n", "Because there are no value type semantics or syntax in Python,\n", "you may need to modify your approach. To revisit the previous example,\n", "we can ensure that the changes we want to make to an array item\n", "aren't \"lost\" by resetting an array member after making changes to it:" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{X=1,Y=0} {X=1,Y=0} 1 1\n" ] } ], "source": [ "items = System.Array.CreateInstance(Point, 3)\n", "for i in range(3):\n", " items[i] = Point(0, 0)\n", "\n", "# This _will_ work. We get 'item' as a boxed copy of the Point\n", "# object actually stored in the array. After making our changes\n", "# we re-set the array item to update the bits in the array.\n", "\n", "item = items[0]\n", "item.X = 1\n", "items[0] = item\n", "print(item, items[0], item.X, items[0].X)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This is not unlike some of the cases you can find in C# where you have to\n", "know about boxing behavior to avoid similar kinds of `lost update` problems\n", "(generally because an implicit boxing happened that was not taken\n", "into account in the code).\n", "\n", "This is the same thing, just the manifestation is a little different\n", "in Python. See the .NET documentation for more details on boxing and the\n", "differences between value types and reference types." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Embedding Python\n", "\n", "**Note:** because Python code running under Python for .NET is inherently\n", "unverifiable, it runs totally under the radar of the security infrastructure\n", "of the CLR so you should restrict use of the Python assembly to trusted code.\n", "\n", "The Python runtime assembly defines a number of public classes that\n", "provide a subset of the functionality provided by the Python C-API.\n", "\n", "These classes include PyObject, PyList, PyDict, PyTuple, etc.\n", "You can review the nPython.exe source code in in \"Console.csproj\" project\n", "for example of embedding CPython in console .NET app. Please refer to\n", "this README GitHub page for new simplified embedding API:\n", "\n", "[README.md][8]\n", "\n", "At a very high level, to embed Python in your application you will need to:\n", "\n", "- Reference Python.Runtime.dll in your build environment\n", "- Call PythonEngine.Intialize() to initialize Python\n", "- Call PythonEngine.ImportModule(name) to import a module\n", "\n", "The module you import can either start working with your managed app\n", "environment at the time its imported, or you can explicitly lookup and\n", "call objects in a module you import.\n", "\n", "For general-purpose information on embedding Python in applications,\n", "use www.python.org or Google to find (C) examples. Because\n", "Python for .NET is so closely integrated with the managed environment,\n", "you will generally be better off importing a module and deferring to\n", "Python code as early as possible rather than writing a lot of managed\n", "embedding code.\n", "\n", "**Important Note for embedders:** Python is not free-threaded and\n", "uses a global interpreter lock to allow multi-threaded applications\n", "to interact safely with the Python interpreter.\n", "Much more information about this is available in the Python C-API\n", "documentation on the www.python.org Website.\n", "\n", "When embedding Python in a managed application, you have to manage the\n", "GIL in just the same way you would when embedding Python in\n", "a C or C++ application.\n", "\n", "Before interacting with any of the objects or APIs provided by the\n", "Python.Runtime namespace, calling code must have acquired the Python\n", "global interpreter lock by calling the `PythonEngine.AcquireLock` method.\n", "The only exception to this rule is the `PythonEngine.Initialize` method,\n", "which may be called at startup without having acquired the GIL.\n", "\n", "When finished using Python APIs, managed code must call a corresponding\n", "`PythonEngine.ReleaseLock` to release the GIL and allow other threads\n", "to use Python.\n", "\n", "The AcquireLock and ReleaseLock methods are thin wrappers over the\n", "unmanaged `PyGILState_Ensure` and `PyGILState_Release` functions from\n", "the Python API, and the documentation for those APIs applies to\n", "the managed versions.\n", "\n", "[8]: https://github.com/pythonnet/pythonnet/blob/master/README.md\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python [conda root]", "language": "python", "name": "conda-root-py" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.3" } }, "nbformat": 4, "nbformat_minor": 2 }
X Tutup