[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/losttech/pythonnet/pythonnet-jupyter-notebook/Python.NET.ipynb [Back]  [Original]

{
 "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 = 0 && index =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

Web Proxy Viewer  |  New URL  |  Original Page