From 45d13c66c94ffaefb5a722ff561cc924bc12ec13 Mon Sep 17 00:00:00 2001 From: Tony Roberts Date: Fri, 26 Jun 2015 10:28:37 +0100 Subject: [PATCH 01/22] Update download link to PyPI Remove link to unofficial windows builds as those are out of date. Future builds will be uploaded to PyPI for windows as well as the source distribution. --- index.html | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/index.html b/index.html index a35cd01..0170f55 100644 --- a/index.html +++ b/index.html @@ -137,12 +137,9 @@

Python for .NET

tests for the package.
  • Checkout the PythonNet code from github.
  • -
  • +
  • Download releases for various versions of Python and CLR.
  • -
  • - Unofficial Windows Binaries can be downloaded here. -
  • From 27d3982c0bd99b296cabc813c7934f33097e6141 Mon Sep 17 00:00:00 2001 From: denfromufa Date: Wed, 14 Sep 2016 09:08:29 -0600 Subject: [PATCH 02/22] Update documentation (#5) --- index.html | 34 ++++++++--------- readme.html | 104 ++++++++++++++++++++-------------------------------- 2 files changed, 56 insertions(+), 82 deletions(-) diff --git a/index.html b/index.html index 0170f55..a731010 100644 --- a/index.html +++ b/index.html @@ -4,7 +4,7 @@ - - - - - - - - - -
    -

    Python for .NET

    -

    Python for .NET (pythonnet) is a package that gives Python programmers - nearly seamless integration with the .NET 4.0+ Common Language Runtime - (CLR) on Windows and Mono runtime on Linux and OSX. - Python for .NET provides a powerful application scripting tool for .NET - developers. Using this package you can script .NET applications or - build entire applications in Python, using .NET services and - components written in any language that targets the CLR (C#, VB.NET, F#, C++/CLI). -

    -

    Note that this package does not implement Python as a - first-class CLR language - it does not produce managed code (IL) - from Python code. Rather, it is an integration of the CPython - engine with the .NET or Mono runtime. This approach allows you to use - CLR services and continue to use existing Python code and C-based - extensions while maintaining native execution speeds for Python - code. If you are interested in a pure managed-code implementation - of the Python language, you should check out the IronPython - project, which is in active development.

    -

    Python for .NET is currently compatible with Python releases 2.7, 3.3, 3.4, 3.5 and 3.6. - To subscribe to the - Python for .NET mailing list or read the - online archives of the list, see the - mailing list information page. You can also send questions - or comments to me at brian.d.lloyd@gmail.com - or use the - Python for .NET issue tracker to report issues.

    -
      -
    • The README provides a detailed - overview of Python for .NET, as well as some basic usage - examples. Many other examples can be found in the demos and unit - tests for the package.
    • -
    • Checkout the PythonNet - code from github.
    • -
    • - Download releases for various versions of Python and CLR. -
    • -
    -
    - - diff --git a/readme.html b/readme.html deleted file mode 100644 index b9ffe54..0000000 --- a/readme.html +++ /dev/null @@ -1,651 +0,0 @@ - - - Codestin Search App - - - - - - - - - - - -
    -

    Python for .NET (pythonnet) is a package that gives Python programmers - nearly seamless integration with the .NET 4.0+ Common Language Runtime - (CLR) on Windows and Mono runtime on Linux and OSX. - Python for .NET provides a powerful application scripting tool for .NET - developers. Using this package you can script .NET applications or - build entire applications in Python, using .NET services and - components written in any language that targets the CLR (C#, VB.NET, F#, C++/CLI). -

    -

    Note that this package does not implement Python as a - first-class CLR language - it does not produce managed code (IL) - from Python code. Rather, it is an integration of the CPython - engine with the .NET or Mono runtime. This approach allows you to use - CLR services and continue to use existing Python code and C-API - extensions while maintaining native execution speeds for Python - code. If you are interested in a pure managed-code implementation - of the Python language, you should check out the IronPython - project, which is in active development. -

    -

    Python for .NET is currently compatible and tested with Python releases 2.7, 3.3, 3.4, 3.5, and 3.6. - Current releases are available at the - Python for .NET website . To subscribe to the - Python for .NET mailing list or read the - online archives of the list, see the - mailing list information page.

    - -

    Installation

    -

    Python for .NET is available as a source release on - GitHub - and as a binary wheel distribution for all supported versions of Python - and the common language runtime from the - Python Package Index . -

    - -

    The source release is a self-contained "private" assembly. Just - unzip the package wherever you want it, cd to that directory, - build the solution python setup.py build_ext --inplace. - Once you start up Python or IPython interpreter in this directory or - append this directory to sys.path, - then after import clr statement .NET assemblies can be used. - You can also run nPython.exe (mono nPython.exe on *nix) - to check how python can be embedded in console .NET application. - Note that the source release does not include a copy of the CPython runtime, - so you will need to have installed Python on your machine before using - the source release. -

    -

    Running on Linux/Mono: Unit testing - shows that PythonNet will run under Mono, - though the Mono runtime is less supported so there still may be - problems. -

    - -

    Getting Started

    -

    A key goal for this project has been that Python for .NET should - "work just the way you'd expect in Python", except for cases that - are .NET specific (in which case the goal is to work "just the way - you'd expect in C#"). In addition, with the IronPython project - having established a community, it is my goal that code written for IronPython - run without modification under Python for .NET. -

    -

    If you already know Python, you can probably finish this readme - and then refer to .NET docs to figure out anything you need to do. - Conversely if you are familiar with C# or another .NET language, - you probably just need to pick up one of the many good Python - books or read the Python tutorial online to get started. -

    -

    A good way to start is to interactively explore - .NET usage in python interpreter by - following along with the examples in this document. If you get stuck, - there are also a number of demos and unit tests located in the - source directory of the distribution that can be helpful as - examples. -

    - -

    Importing Modules

    -

    Python for .NET allows CLR namespaces to be treated essentially - as Python packages.

    -

    -

    -
        from System import String
    -    from System.Collections import *
    -
    -

    Types from any loaded assembly may be imported and used in this - manner. To load an assembly, use the "AddReference" function in - the "clr" module: -

    -
    -    import clr
    -    clr.AddReference("System.Windows.Forms")
    -    from System.Windows.Forms import Form
    -
    -
    -

    - Note that earlier releases of Python for .NET relied on - "implicit loading" to support automatic loading of assemblies - whose names corresponded to an imported namespace. Implicit - loading still works for backward compatibility, but will be - removed in a future release so it is recommended to use the - clr.AddReference method. - -

    -

    Python for .NET uses the PYTHONPATH (sys.path) to look for - assemblies to load, in addition to the usual application base and - the GAC. To ensure that you can implicitly import an assembly, put - the directory containing the assembly in sys.path. -

    - -

    Using Classes

    -

    Python for .NET allows you to use any non-private classes, - structs, interfaces, enums or delegates from Python. To create an - instance of a managed class, you use the standard instantiation - syntax, passing a set of arguments that match one of its public - constructors: -

    -
        from System.Drawing import Point
    -
    -    p = Point(5, 5)
    -
    -

    In most cases, Python for .NET can determine the correct - constructor to call automatically based on the arguments. In some - cases, it may be necessary to call a particular overloaded - constructor, which is supported by a special "__overloads__" - attribute, which will soon be deprecated in favor of iPy - compatible "Overloads", on a class: -

    -
        from System import String, Char, Int32
    -
    -    s = String.Overloads[Char, Int32]('A', 10)
    -    s = String.__overloads__[Char, Int32]('A', 10)
    -
    - -

    Using Generics

    -

    Pythonnet also supports generic types. A generic type must be bound to - create a concrete type before it can be instantiated. Generic - types support the subscript syntax to create bound types: -

    -
        from System.Collections.Generic import Dictionary
    -    from System import *
    -
    -    dict1 = Dictionary[String, String]()
    -    dict2 = Dictionary[String, Int32]()
    -    dict3 = Dictionary[String, Type]()
    -
    -

    When you pass a list of types using the subscript syntax, you - can also pass a subset of Python types that directly correspond to - .NET types: -

    -
        dict1 = Dictionary[str, str]()
    -    dict2 = Dictionary[str, int]()
    -    dict3 = Dictionary[str, Decimal]()
    -
    -

    This shorthand also works when explicitly selecting generic - methods or specific versions of overloaded methods and - constructors (explained later). -

    -

    You can also subclass managed classes in Python, though members - of the Python subclass are not visible to .NET code. See the helloform.py - file in the /demo directory of the distribution for - a simple Windows Forms example that demonstrates subclassing a - managed class. -

    - -

    Fields And Properties

    -

    You can get and set fields and properties of CLR objects just as - if they were regular attributes: -

    -
        from System import Environment
    -
    -    name = Environment.MachineName
    -    Environment.ExitCode = 1
    -
    - -

    Using Indexers

    -

    If a managed object implements one or more indexers, you can - call the indexer using standard Python indexing syntax: -

    -
        from System.Collections import Hashtable
    -
    -    table = Hashtable()
    -    table["key 1"] = "value 1"
    -
    -

    Overloaded indexers are supported, using the same notation one - would use in C#: -

    -
        items[0, 2]
    -
    -    items[0, 2, 3]
    -
    - -

    Using Methods

    -

    Methods of CLR objects behave generally like normal Python - methods. Static methods may be called either through the class or - through an instance of the class. All public and protected methods - of CLR objects are accessible to Python: -

    -
        from System import Environment
    -
    -    drives = Environment.GetLogicalDrives()
    -
    -

    It is also possible to call managed methods unbound - (passing the instance as the first argument) just as with Python - methods. This is most often used to explicitly call methods of a - base class. -

    -

    Note that there is one caveat related to calling unbound - methods: it is possible for a managed class to declare a static - method and an instance method with the same name. Since it is - not possible for the runtime to know the intent when such a - method is called unbound, the static method will always be - called. -

    -

    The docstring of CLR a method (__doc__) can be used to view the - signature of the method, including overloads if the CLR method is - overloaded. You can also use the Python help method - to inspect a managed class: -

    -
        from System import Environment
    -
    -    print(Environment.GetFolderPath.__doc__)
    -
    -    help(Environment)
    -
    - -

    Overloaded and Generic Methods

    -

    While Python for .NET will generally be able to figure out the - right version of an overloaded method to call automatically, there - are cases where it is desirable to select a particular method - overload explicitly. -

    -

    Methods of CLR objects have an "__overloads__", which will soon - be deprecated in favor of iPy compatible Overloads, attribute that - can be used for this purpose : -

    -
        from System import Console
    -
    -    Console.WriteLine.Overloads[bool](true)
    -    Console.WriteLine.Overloads[str]("true")
    -    Console.WriteLine.__overloads__[int](42)
    -
    -

    Similarly, generic methods may be bound at runtime using the - subscript syntax directly on the method: -

    -
        someobject.SomeGenericMethod[int](10)
    -    someobject.SomeGenericMethod[str]("10")
    -
    - -

    Delegates And Events

    -

    Delegates defined in managed code can be implemented in Python. - A delegate type can be instantiated and passed a callable Python - object to get a delegate instance. The resulting delegate instance - is a true managed delegate that will invoke the given Python - callable when it is called: -

    -
        def my_handler(source, args):
    -        print('my_handler called!')
    -
    -    # instantiate a delegate
    -    d = AssemblyLoadEventHandler(my_handler)
    -
    -    # use it as an event handler
    -    AppDomain.CurrentDomain.AssemblyLoad += d
    -
    -

    Multicast delegates can be implemented by adding more callable - objects to a delegate instance: -

    -
        d += self.method1
    -    d += self.method2
    -    d()
    -
    -

    Events are treated as first-class objects in Python, and behave - in many ways like methods. Python callbacks can be registered with - event attributes, and an event can be called to fire the event. -

    -

    Note that events support a convenience spelling similar to that - used in C#. You do not need to pass an explicitly instantiated - delegate instance to an event (though you can if you want). Events - support the += and -= operators in a - way very similar to the C# idiom: -

    -
        def handler(source, args):
    -        print('my_handler called!')
    -
    -    # register event handler
    -    object.SomeEvent += handler
    -
    -    # unregister event handler
    -    object.SomeEvent -= handler
    -
    -    # fire the event
    -    result = object.SomeEvent(...)
    -
    - -

    Exception Handling

    -

    You can raise and catch managed exceptions just the same as you - would pure-Python exceptions: -

    -
        from System import NullReferenceException
    -
    -    try:
    -        raise NullReferenceException("aiieee!")
    -    except NullReferenceException as e:
    -        print(e.Message)
    -        print(e.Source)
    -
    -

    - -

    Using Arrays

    -

    The type System.Array supports the subscript - syntax in order to make it easy to create managed arrays from - Python: -

    -
        from System import Array
    -
    -    myarray = Array[int](10)
    -
    -

    Managed arrays support the standard Python sequence protocols: -

    -
        items = SomeObject.GetArray()
    -
    -    # Get first item
    -    v = items[0]
    -    items[0] = v
    -
    -    # Get last item
    -    v = items[-1]
    -    items[-1] = v
    -
    -    # Get length
    -    l = len(items)
    -
    -    # Containment test
    -    test = v in items
    -
    -

    Multidimensional arrays support indexing using the same notation - one would use in C#: -

    -
        items[0, 2]
    -
    -    items[0, 2, 3]
    -
    - -

    Using Collections

    -

    Managed arrays and managed objects that implement the - IEnumerable interface can be iterated over using the standard - iteration Python idioms: -

    -
        domain = System.AppDomain.CurrentDomain
    -
    -    for item in domain.GetAssemblies():
    -        name = item.GetName()
    -
    - -

    Using COM Components

    -

    Using Microsoft-provided tools such as aximp.exe - and tlbimp.exe, it is possible to generate - managed wrappers for COM libraries. After generating such a - wrapper, you can use the libraries from Python just like any other - managed code. -

    -

    Note: currently you need to put the generated wrappers in the - GAC, in the PythonNet assembly directory or on the PYTHONPATH in - order to load them. -

    - -

    Type Conversion

    -

    Type conversion under Python for .NET is fairly straightforward - - most elemental Python types (string, int, long, etc.) convert - automatically to compatible managed equivalents (String, Int32, - etc.) and vice-versa. Note that all strings returned from the CLR - are returned as unicode. -

    -

    Types that do not have a logical equivalent in Python are - exposed as instances of managed classes or structs (System.Decimal - is an example). -

    -

    The .NET architecture makes a distinction between value - types and reference types. Reference types - are allocated on the heap, and value types are allocated either on - the stack or in-line within an object. -

    -

    A process called boxing is used in .NET to allow - code to treat a value type as if it were a reference type. Boxing - causes a separate copy of the value type object to be created on - the heap, which then has reference type semantics. -

    -

    Understanding boxing and the distinction between value types and - reference types can be important when using Python for .NET - because the Python language has no value type semantics or syntax - - in Python "everything is a reference". -

    -

    Here is a simple example that demonstrates an issue. If you are - an experienced C# programmer, you might write the following code: -

    -
        items = System.Array.CreateInstance(Point, 3)
    -    for i in range(3):
    -        items[i] = Point(0, 0)
    -
    -    items[0].X = 1 # won't work!!
    -
    -

    While the spelling of items[0].X = 1 is the same - in C# and Python, there is an important and subtle semantic - difference. In C# (and other compiled-to-IL languages), the - compiler knows that Point is a value type and can do the Right - Thing here, changing the value in place. -

    -

    In Python however, "everything's a reference", and there is - really no spelling or semantic to allow it to do the right thing - dynamically. The specific reason that items[0] - itself doesn't change is that when you say items[0], - that getitem operation creates a Python object that holds a - reference to the object at items[0] via a GCHandle. - That causes a ValueType (like Point) to be boxed, so the following - setattr (.X = 1) changes the state of the boxed - value, not the original unboxed value. -

    -

    The rule in Python is essentially: "the result of any attribute - or item access is a boxed value", and that can be important in how - you approach your code. -

    -

    Because there are no value type semantics or syntax in Python, - you may need to modify your approach. To revisit the previous - example, we can ensure that the changes we want to make to an - array item aren't "lost" by resetting an array member after making - changes to it: -

    -
        items = System.Array.CreateInstance(Point, 3)
    -    for i in range(3):
    -        items[i] = Point(0, 0)
    -
    -    # This _will_ work. We get 'item' as a boxed copy of the Point
    -    # object actually stored in the array. After making our changes
    -    # we re-set the array item to update the bits in the array.
    -
    -    item = items[0]
    -    item.X = 1
    -    items[0] = item
    -
    -

    This is not unlike some of the cases you can find in C# where - you have to know about boxing behavior to avoid similar kinds of lost - update problems (generally because an implicit boxing - happened that was not taken into account in the code). -

    -

    This is the same thing, just the manifestation is a little - different in Python. See the .NET documentation for more details - on boxing and the differences between value types and reference - types. -

    - -

    Embedding Python

    -

    Note: because Python code running under Python - for .NET is inherently unverifiable, it runs totally under the - radar of the security infrastructure of the CLR so you should - restrict use of the Python assembly to trusted code. -

    -

    The Python runtime assembly defines a number of public classes - that provide a subset of the functionality provided by the Python - C-API. -

    -

    These classes include PyObject, PyList, PyDict, PyTuple, etc. - You can review the nPython.exe source code in in "Console.csproj" project - for example of embedding CPython in console .NET app. - Please refer to this README GitHub page for new simplified embedding API: -

    -

    - README.md -

    -

    At a very high level, to embed Python in your application you - will need to: -

    -
      -
    • Reference Python.Runtime.dll in your build environment
    • -
    • Call PythonEngine.Intialize() to initialize Python
    • -
    • Call PythonEngine.ImportModule(name) to import a module
    • -
    -

    The module you import can either start working with your managed - app environment at the time its imported, or you can explicitly - lookup and call objects in a module you import. -

    -

    For general-purpose information on embedding Python in - applications, use www.python.org or Google to find (C) examples. - Because Python for .NET is so closely integrated with the managed - environment, you will generally be better off importing a module - and deferring to Python code as early as possible rather than - writing a lot of managed embedding code. -

    -

    Important Note for embedders: Python is not - free-threaded and uses a global interpreter lock to allow - multi-threaded applications to interact safely with the Python - interpreter. Much more information about this is available in the - Python C-API documentation on the www.python.org Website. -

    -

    When embedding Python in a managed application, you have to - manage the GIL in just the same way you would when embedding - Python in a C or C++ application. -

    -

    Before interacting with any of the objects or APIs provided by - the Python.Runtime namespace, calling code must have acquired the - Python global interpreter lock by calling the PythonEngine.AcquireLock - method. The only exception to this rule is the PythonEngine.Initialize - method, which may be called at startup without having acquired the - GIL. -

    -

    When finished using Python APIs, managed code must call a - corresponding PythonEngine.ReleaseLock to release - the GIL and allow other threads to use Python. -

    -

    The AcquireLock and ReleaseLock methods are thin wrappers over - the unmanaged PyGILState_Ensure and PyGILState_Release - functions from the Python API, and the documentation for those - APIs applies to the managed versions. -

    - -

    License

    -
    -

    Python for .NET is released under the open - source MIT License. A copy of the license is included - in the distribution, or you can find a copy of the - license online . Some distributions of this package include a - copy of the C Python dlls and standard library, which are covered - by the Python - license . -

    -
    - - From a4e4ddd620934d07e4f556cb29ef73272eec8873 Mon Sep 17 00:00:00 2001 From: Matthias Reitinger Date: Mon, 31 Jul 2017 10:30:55 +0200 Subject: [PATCH 07/22] Remove README dead link (#9) The link to the README is dead. It can be removed, because the index and readme pages were merged some time ago (#8). --- README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/README.md b/README.md index 1373a60..1415cc4 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ To subscribe to the [Python for .NET mailing list][3] or read the [online archives][4] of the list, see the [mailing list information][3] page. Use the [Python for .NET issue tracker][55] to report issues. -- The [README][66] provides a detailed overview of Python for .NET, +- This page provides a detailed overview of Python for .NET, as well as some basic usage examples. Many other examples can be found in the demos and unit tests for the package. - Checkout the [PythonNet][77] code from github. @@ -555,6 +555,4 @@ standard library, which are covered by the [Python license][10]. [55]: http://github.com/pythonnet/pythonnet/issues -[66]: http://pythonnet.github.io/readme.html - [77]: http://github.com/pythonnet/pythonnet From cefba0ede955c7af137841f1d54417125c667c35 Mon Sep 17 00:00:00 2001 From: jbw3 <> Date: Sat, 7 Jul 2018 18:17:05 -0500 Subject: [PATCH 08/22] Adding more C# examples --- README.md | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 62 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1415cc4..08b65b6 100644 --- a/README.md +++ b/README.md @@ -517,13 +517,74 @@ which may be called at startup without having acquired the GIL. When finished using Python APIs, managed code must call a corresponding `PythonEngine.ReleaseLock` to release the GIL and allow other threads -to use Python. +to use Python: + +```csharp +IntPtr gilState = PythonEngine.AcquireLock(); + +PythonEngine.Exec("doStuff()"); + +PythonEngine.ReleaseLock(gilState); +``` + +A `using` statement may also be used to acquire and release the GIL: + +```csharp +using (Py.GIL()) +{ + PythonEngine.Exec("doStuff()"); +} +``` The AcquireLock and ReleaseLock methods are thin wrappers over the unmanaged `PyGILState_Ensure` and `PyGILState_Release` functions from the Python API, and the documentation for those APIs applies to the managed versions. +## Passing C# Objects to the Python Engine + +This section demonstrates how to pass a C# object to the Python runtime. +The example uses the following `Person` class: + +```csharp +public class Person +{ + public Person(string firstName, string lastName) + { + FirstName = firstName; + LastName = lastName; + } + + public string FirstName { get; set; } + public string LastName { get; set; } +} +``` + +In order to pass a C# object to the Python runtime, it must be converted to a +`PyObject`. This is done using the `ToPython` extension method. The `PyObject` +may then be added to a dictionary of local variables and passed to the +`PythonEngine.Exec` function: + +```csharp +// create a person object +Person person = new Person("John", "Smith"); + +// acquire the GIL before using the Python interpreter +using (Py.GIL()) +{ + // convert the Person object to a PyObject + PyObject pyPerson = person.ToPython(); + + // create a Python variable "person" + PyDict locals = new PyDict(); + locals["person"] = pyPerson; + + // the person object may now be used in Python + string code = "fullName = person.FirstName + ' ' + person.LastName"; + PythonEngine.Exec(code, null, locals.Handle); +} +``` + ## License Python for .NET is released under the open source MIT License. From c7c7379674abc19b02cb14a751aa54e932d018db Mon Sep 17 00:00:00 2001 From: jbw3 <> Date: Mon, 20 Aug 2018 20:49:30 -0500 Subject: [PATCH 09/22] Addressing code review comments --- README.md | 37 ++++++++++++++++--------------------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 08b65b6..23b5103 100644 --- a/README.md +++ b/README.md @@ -517,17 +517,9 @@ which may be called at startup without having acquired the GIL. When finished using Python APIs, managed code must call a corresponding `PythonEngine.ReleaseLock` to release the GIL and allow other threads -to use Python: +to use Python. -```csharp -IntPtr gilState = PythonEngine.AcquireLock(); - -PythonEngine.Exec("doStuff()"); - -PythonEngine.ReleaseLock(gilState); -``` - -A `using` statement may also be used to acquire and release the GIL: +A `using` statement may be used to acquire and release the GIL: ```csharp using (Py.GIL()) @@ -561,9 +553,9 @@ public class Person ``` In order to pass a C# object to the Python runtime, it must be converted to a -`PyObject`. This is done using the `ToPython` extension method. The `PyObject` -may then be added to a dictionary of local variables and passed to the -`PythonEngine.Exec` function: +`PyObject`. This is done using the `ToPython()` extension method. The `PyObject` +may then be set as a variable in a `PyScope`. Code executed from the scope +will have access to the variable: ```csharp // create a person object @@ -572,16 +564,19 @@ Person person = new Person("John", "Smith"); // acquire the GIL before using the Python interpreter using (Py.GIL()) { - // convert the Person object to a PyObject - PyObject pyPerson = person.ToPython(); + // create a Python scope + using (PyScope scope = Py.CreateScope()) + { + // convert the Person object to a PyObject + PyObject pyPerson = person.ToPython(); - // create a Python variable "person" - PyDict locals = new PyDict(); - locals["person"] = pyPerson; + // create a Python variable "person" + scope.Set("person", pyPerson); - // the person object may now be used in Python - string code = "fullName = person.FirstName + ' ' + person.LastName"; - PythonEngine.Exec(code, null, locals.Handle); + // the person object may now be used in Python + string code = "fullName = person.FirstName + ' ' + person.LastName"; + scope.Exec(code); + } } ``` From 6077016a37f4651928a56e83e79cef29ee099f79 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Mon, 3 Jun 2019 17:25:40 +0200 Subject: [PATCH 10/22] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 23b5103..80eaecf 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ implementation of the Python language, you should check out the [IronPython][1] project, which is in active development. Python for .NET is currently compatible and tested with Python releases -`2.7`, `3.3`, `3.4`, `3.5`, and `3.6`. +2.7 and 3.5-3.7. Current releases are available at the [Python for .NET website][2]. To subscribe to the [Python for .NET mailing list][3] or read the [online archives][4] of the list, see the [mailing list information][3] From 686da1449e93ec4ab4fa9a2bba5296a2f3c7539b Mon Sep 17 00:00:00 2001 From: Ayoub Kaanich Date: Sat, 5 Oct 2019 12:47:24 +0200 Subject: [PATCH 11/22] Fix typo in __overloads__ --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 80eaecf..b6c582e 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,7 @@ iPy compatible "Overloads", on a class: from System import String, Char, Int32 s = String.Overloads[Char, Int32]('A', 10) -s = String.__overloads[__Char, Int32]('A', 10) +s = String.__overloads__[Char, Int32]('A', 10) ``` ## Using Generics @@ -242,7 +242,7 @@ from System import Console Console.WriteLine.Overloads[bool](true) Console.WriteLine.Overloads[str]("true") -Console.WriteLine.__overloads[__int](42) +Console.WriteLine.__overloads__[int](42) ``` Similarly, generic methods may be bound at runtime using the subscript From 897b781d02c1fa715a5e69c6fd174ac9b569b9b2 Mon Sep 17 00:00:00 2001 From: Ayoub Kaanich Date: Tue, 5 Nov 2019 22:46:50 +0100 Subject: [PATCH 12/22] Fix broken link --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b6c582e..58fb843 100644 --- a/README.md +++ b/README.md @@ -480,7 +480,7 @@ You can review the nPython.exe source code in in "Console.csproj" project for example of embedding CPython in console .NET app. Please refer to this README GitHub page for new simplified embedding API: -[README.md][8] +[README.rst][8] At a very high level, to embed Python in your application you will need to: @@ -603,7 +603,7 @@ standard library, which are covered by the [Python license][10]. [7]: http://www.go-mono.com -[8]: https://github.com/pythonnet/pythonnet/blob/master/README.md +[8]: https://github.com/pythonnet/pythonnet/blob/master/README.rst#embedding-python-in-net [9]: http://pythonnet.github.io/LICENSE From c5ee26e29b3ddbc121ce6e2baba05ae04cb53988 Mon Sep 17 00:00:00 2001 From: Alex Earl Date: Sun, 12 Jan 2020 03:22:05 -0700 Subject: [PATCH 13/22] Fix typo (#16) Fixes typo in `Initialize` method name. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 58fb843..309d9c1 100644 --- a/README.md +++ b/README.md @@ -485,7 +485,7 @@ this README GitHub page for new simplified embedding API: At a very high level, to embed Python in your application you will need to: - Reference Python.Runtime.dll in your build environment -- Call PythonEngine.Intialize() to initialize Python +- Call PythonEngine.Initialize() to initialize Python - Call PythonEngine.ImportModule(name) to import a module The module you import can either start working with your managed app From 601105597369c09f79cf5aa487fbc95e7e7bdf36 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Mon, 18 May 2020 12:34:55 +0200 Subject: [PATCH 14/22] Update README.md --- README.md | 54 +++++++++++++++++++++++++++++------------------------- 1 file changed, 29 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 309d9c1..dba1d49 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ -# Python for .NET +# Python.NET -Python for .NET (`pythonnet`) is a package that gives Python programmers +Python.NET (`pythonnet`) is a package that gives Python programmers nearly seamless integration with the .NET 4.0+ Common Language Runtime -(CLR) on Windows and Mono runtime on Linux and OSX. Python for .NET +(CLR) on Windows and Mono runtime on Linux and OSX. Python.NET provides a powerful application scripting tool for .NET developers. Using this package you can script .NET applications or build entire applications in Python, using .NET services and components written in @@ -17,14 +17,14 @@ speeds for Python code. If you are interested in a pure managed-code implementation of the Python language, you should check out the [IronPython][1] project, which is in active development. -Python for .NET is currently compatible and tested with Python releases -2.7 and 3.5-3.7. -Current releases are available at the [Python for .NET website][2]. -To subscribe to the [Python for .NET mailing list][3] or read the +Python.NET is currently compatible and tested with Python releases +2.7 and 3.5-3.8. +Current releases are available at the [Python.NET website][2]. +To subscribe to the [Python.NET mailing list][3] or read the [online archives][4] of the list, see the [mailing list information][3] -page. Use the [Python for .NET issue tracker][55] to report issues. +page. Use the [Python.NET issue tracker][55] to report issues. -- This page provides a detailed overview of Python for .NET, +- This page provides a detailed overview of Python.NET, as well as some basic usage examples. Many other examples can be found in the demos and unit tests for the package. - Checkout the [PythonNet][77] code from github. @@ -32,7 +32,7 @@ page. Use the [Python for .NET issue tracker][55] to report issues. ## Installation -Python for .NET is available as a source release on [GitHub][5] and as a +Python.NET is available as a source release on [GitHub][5] and as a binary wheel distribution for all supported versions of Python and the common language runtime from the [Python Package Index][6]. @@ -53,12 +53,12 @@ may be problems. ## Getting Started -A key goal for this project has been that Python for .NET should +A key goal for this project has been that Python.NET should "work just the way you'd expect in Python", except for cases that are .NET specific (in which case the goal is to work "just the way you'd expect in C#"). In addition, with the IronPython project having established a community, it is my goal that code written for IronPython -run without modification under Python for .NET. +run without modification under Python.NET. If you already know Python, you can probably finish this readme and then refer to .NET docs to figure out anything you need to do. Conversely if @@ -73,7 +73,7 @@ source directory of the distribution that can be helpful as examples. ## Importing Modules -Python for .NET allows CLR namespaces to be treated essentially as +Python.NET allows CLR namespaces to be treated essentially as Python packages. ```python @@ -90,20 +90,20 @@ clr.AddReference("System.Windows.Forms") from System.Windows.Forms import Form ``` -**Note** Earlier releases of Python for .NET relied on "implicit loading" +**Note** Earlier releases of Python.NET relied on "implicit loading" to support automatic loading of assemblies whose names corresponded to an imported namespace. Implicit loading still works for backward compatibility, but will be removed in a future release so it is recommended to use the `clr.AddReference` method. -Python for .NET uses the PYTHONPATH (sys.path) to look for assemblies +Python.NET uses the PYTHONPATH (sys.path) to look for assemblies to load, in addition to the usual application base and the GAC. To ensure that you can implicitly import an assembly, put the directory containing the assembly in `sys.path`. ## Using Classes -Python for .NET allows you to use any non-private classes, structs, +Python.NET allows you to use any non-private classes, structs, interfaces, enums or delegates from Python. To create an instance of a managed class, you use the standard instantiation syntax, passing a set of arguments that match one of its public constructors: @@ -114,7 +114,7 @@ from System.Drawing import Point p = Point(5, 5) ``` -In most cases, Python for .NET can determine the correct constructor to +In most cases, Python.NET can determine the correct constructor to call automatically based on the arguments. In some cases, it may be necessary to call a particular overloaded constructor, which is supported by a special `__overloads__` attribute, which will soon be deprecated in favor of @@ -229,7 +229,7 @@ help(Environment) ## Overloaded and Generic Methods -While Python for .NET will generally be able to figure out the right +While Python.NET will generally be able to figure out the right version of an overloaded method to call automatically, there are cases where it is desirable to select a particular method overload explicitly. @@ -384,7 +384,7 @@ the PythonNet assembly directory or on the PYTHONPATH in order to load them. ## Type Conversion -Type conversion under Python for .NET is fairly straightforward - most +Type conversion under Python.NET is fairly straightforward - most elemental Python types (string, int, long, etc.) convert automatically to compatible managed equivalents (String, Int32, etc.) and vice-versa. Note that all strings returned from the CLR are returned as unicode. @@ -402,7 +402,7 @@ value type object to be created on the heap, which then has reference type semantics. Understanding boxing and the distinction between value types and reference -types can be important when using Python for .NET because the Python +types can be important when using Python.NET because the Python language has no value type semantics or syntax - in Python "everything is a reference". @@ -468,7 +468,7 @@ differences between value types and reference types. ## Embedding Python -**Note:** because Python code running under Python for .NET is inherently +**Note:** because Python code running under Python.NET is inherently unverifiable, it runs totally under the radar of the security infrastructure of the CLR so you should restrict use of the Python assembly to trusted code. @@ -494,7 +494,7 @@ call objects in a module you import. For general-purpose information on embedding Python in applications, use www.python.org or Google to find (C) examples. Because -Python for .NET is so closely integrated with the managed environment, +Python.NET is so closely integrated with the managed environment, you will generally be better off importing a module and deferring to Python code as early as possible rather than writing a lot of managed embedding code. @@ -582,20 +582,24 @@ using (Py.GIL()) ## License -Python for .NET is released under the open source MIT License. +Python.NET is released under the open source MIT License. A copy of the license is included in the distribution, or you can find a copy of the [license online][9]. Some distributions of this package include a copy of the C Python dlls and standard library, which are covered by the [Python license][10]. +## .NET Foundation + +This project is supported by the [.NET Foundation](https://dotnetfoundation.org). + [1]: http://www.ironpython.com [2]: http://pythonnet.github.io/ -[3]: http://mail.python.org/mailman/listinfo/pythondotnet +[3]: https://mail.python.org/mailman3/lists/pythonnet.python.org/ -[4]: http://mail.python.org/pipermail/pythondotnet/ +[4]: https://mail.python.org/archives/list/pythonnet@python.org/ [5]: https://github.com/pythonnet/pythonnet/releases From c7003910c6a3903abd384aa384604fb9e6c2cdef Mon Sep 17 00:00:00 2001 From: Christabella Irwanto Date: Wed, 2 Dec 2020 08:27:19 +0000 Subject: [PATCH 15/22] Add link to installation wiki page It was a source of confusion in the beginning when I took the website as the source of truth --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index dba1d49..3d25450 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,8 @@ page. Use the [Python.NET issue tracker][55] to report issues. - [Download releases][6] for various versions of Python and CLR. ## Installation +Please refer to [the project wiki][78] for more detailed installation +instructions. Python.NET is available as a source release on [GitHub][5] and as a binary wheel distribution for all supported versions of Python and the @@ -616,3 +618,5 @@ This project is supported by the [.NET Foundation](https://dotnetfoundation.org) [55]: http://github.com/pythonnet/pythonnet/issues [77]: http://github.com/pythonnet/pythonnet + +[78]: https://github.com/pythonnet/pythonnet/wiki/Installation From e5f510aa0814e9d854ac271734205a6df82337b3 Mon Sep 17 00:00:00 2001 From: Tom Minka <8955276+tminka@users.noreply.github.com> Date: Thu, 28 Jan 2021 11:29:23 +0000 Subject: [PATCH 16/22] Added section on Out and Ref parameters (#19) --- .gitignore | 3 +++ README.md | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/.gitignore b/.gitignore index 80184f7..5688596 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,6 @@ _site/ .sass-cache/ .jekyll-metadata + +# Visual Studio cache/options directory +.vs/ diff --git a/README.md b/README.md index 3d25450..d1b5f88 100644 --- a/README.md +++ b/README.md @@ -255,6 +255,33 @@ someobject.SomeGenericMethod[int](10) someobject.SomeGenericMethod[str]("10") ``` +## Out and Ref parameters + +When a managed method has `out` or `ref` parameters, the arguments appear as +normal arguments in Python, but the return value of the method is modified. +There are 3 cases: + +1. If the method is `void` and has one `out` or `ref` parameter, the method returns +the value of that parameter to Python. For example, if `someobject` has +a managed method with signature `void SomeMethod1(out arg)`, it is called like so: +``` +new_arg = someobject.SomeMethod1(arg) +``` +where the value of `arg` is ignored, but its type is used for overload resolution. + +2. If the method is `void` and has multiple `out`/`ref` parameters, the method returns +a tuple containing the `out`/`ref` parameter values. For example, if `someobject` has +a managed method with signature `void SomeMethod2(out arg, ref arg2)`, it is called like so: +``` +new_arg, new_arg2 = someobject.SomeMethod2(arg, arg2) +``` + +3. Otherwise, the method returns a tuple containing the return value followed by the +`out`/`ref` parameter values. For example: +``` +found, new_value = dictionary.TryGetValue(key, value) +``` + ## Delegates And Events Delegates defined in managed code can be implemented in Python. @@ -274,6 +301,9 @@ d = AssemblyLoadEventHandler(my_handler) AppDomain.CurrentDomain.AssemblyLoad += d ``` +Delegates with `out` or `ref` parameters can be implemented in Python by +following the convention described in [Out and Ref parameters]. + Multicast delegates can be implemented by adding more callable objects to a delegate instance: From 77af777a469fc80e1be6729741335c22d7032eff Mon Sep 17 00:00:00 2001 From: CharlieArc Date: Sat, 29 May 2021 13:30:56 -0700 Subject: [PATCH 17/22] Update Getting Started to refer to wiki on GitHub (#20) The wiki on GitHub is a great resource especially for new Python.NET users. Make sure the 'Getting Started' section lists it along with other examples so a new user can find all the awesomesauce there (e.g. "Calling a Dynamic Library", short and extended tutorials, etc.) --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index d1b5f88..47189ce 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,7 @@ A good way to start is to interactively explore .NET usage in python interpreter by following along with the examples in this document. If you get stuck, there are also a number of demos and unit tests located in the source directory of the distribution that can be helpful as examples. +Additionally, refer to the [wiki on GitHub][79], especially the **Tutorials** there. ## Importing Modules @@ -650,3 +651,5 @@ This project is supported by the [.NET Foundation](https://dotnetfoundation.org) [77]: http://github.com/pythonnet/pythonnet [78]: https://github.com/pythonnet/pythonnet/wiki/Installation + +[79]: https://github.com/pythonnet/pythonnet/wiki From 0f523abbc70e79d42fb0529cf6aa5b4e103d1f00 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Fri, 30 Sep 2022 01:38:16 +0200 Subject: [PATCH 18/22] Update README.md --- README.md | 645 ++++-------------------------------------------------- 1 file changed, 37 insertions(+), 608 deletions(-) diff --git a/README.md b/README.md index 47189ce..683f0d4 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # Python.NET Python.NET (`pythonnet`) is a package that gives Python programmers -nearly seamless integration with the .NET 4.0+ Common Language Runtime -(CLR) on Windows and Mono runtime on Linux and OSX. Python.NET +nearly seamless integration with .NET Framework, .NET Core and Mono +runtime on Windows, Linux and macOS. Python.NET provides a powerful application scripting tool for .NET developers. Using this package you can script .NET applications or build entire applications in Python, using .NET services and components written in @@ -10,646 +10,75 @@ any language that targets the CLR (C#, VB.NET, F#, C++/CLI). Note that this package does _not_ implement Python as a first-class CLR language - it does not produce managed code (IL) from Python code. Rather, -it is an integration of the CPython engine with the .NET or Mono runtime. -This approach allows you to use CLR services and continue to use existing +it is an integration of the CPython engine with a .NET runtime. +This approach allows one to use CLR services and continue to use existing Python code and C-API extensions while maintaining native execution speeds for Python code. If you are interested in a pure managed-code implementation of the Python language, you should check out the -[IronPython][1] project, which is in active development. +[IronPython][ipy] project, which is in active development. Python.NET is currently compatible and tested with Python releases -2.7 and 3.5-3.8. -Current releases are available at the [Python.NET website][2]. -To subscribe to the [Python.NET mailing list][3] or read the -[online archives][4] of the list, see the [mailing list information][3] -page. Use the [Python.NET issue tracker][55] to report issues. +3.7 - 3.10. + +To subscribe to the [Python.NET mailing list][ml] or read the +[online archives][ml-arch] of the list, see the [mailing list information][ml] +page. Use the [Python.NET issue tracker][gh-issues] to report issues. - This page provides a detailed overview of Python.NET, as well as some basic usage examples. Many other examples can be found in the demos and unit tests for the package. -- Checkout the [PythonNet][77] code from github. -- [Download releases][6] for various versions of Python and CLR. +- Checkout the [Python.NET][repo] code from github. +- [Download releases][gh-release] ## Installation -Please refer to [the project wiki][78] for more detailed installation -instructions. - -Python.NET is available as a source release on [GitHub][5] and as a -binary wheel distribution for all supported versions of Python and the -common language runtime from the [Python Package Index][6]. - -The source release is a self-contained "private" assembly. Just unzip the -package wherever you want it, cd to that directory, build the solution -`python setup.py build_ext --inplace`. Once you start up Python or -IPython interpreter in this directory or append this directory to -`sys.path`, then after `import clr` statement .NET assemblies can -be used. -You can also run `nPython.exe` (`mono nPython.exe` on `*nix`) to check -how python can be embedded in console .NET application. Note that the -source release does not include a copy of the CPython runtime, so you will -need to have installed Python on your machine before using the source release. - -**Running on Linux/Mono:** Unit testing shows that PythonNet will run -under [Mono][7], though the Mono runtime is less supported so there still -may be problems. - -## Getting Started - -A key goal for this project has been that Python.NET should -"work just the way you'd expect in Python", except for cases that are -.NET specific (in which case the goal is to work "just the way -you'd expect in C#"). In addition, with the IronPython project having -established a community, it is my goal that code written for IronPython -run without modification under Python.NET. - -If you already know Python, you can probably finish this readme and then -refer to .NET docs to figure out anything you need to do. Conversely if -you are familiar with C# or another .NET language, you probably just need -to pick up one of the many good Python books or read the Python tutorial -online to get started. - -A good way to start is to interactively explore .NET usage in python -interpreter by following along with the examples in this document. If you -get stuck, there are also a number of demos and unit tests located in the -source directory of the distribution that can be helpful as examples. -Additionally, refer to the [wiki on GitHub][79], especially the **Tutorials** there. - -## Importing Modules - -Python.NET allows CLR namespaces to be treated essentially as -Python packages. - -```python -from System import String -from System.Collections import * -``` - -Types from any loaded assembly may be imported and used in this manner. -To load an assembly, use the `AddReference` function in the `clr` module: - -```python -import clr -clr.AddReference("System.Windows.Forms") -from System.Windows.Forms import Form -``` - -**Note** Earlier releases of Python.NET relied on "implicit loading" -to support automatic loading of assemblies whose names corresponded to an -imported namespace. Implicit loading still works for backward compatibility, -but will be removed in a future release so it is recommended to use -the `clr.AddReference` method. - -Python.NET uses the PYTHONPATH (sys.path) to look for assemblies -to load, in addition to the usual application base and the GAC. To ensure -that you can implicitly import an assembly, put the directory containing -the assembly in `sys.path`. - -## Using Classes - -Python.NET allows you to use any non-private classes, structs, -interfaces, enums or delegates from Python. To create an instance of a -managed class, you use the standard instantiation syntax, passing a set -of arguments that match one of its public constructors: - -```python -from System.Drawing import Point - -p = Point(5, 5) -``` - -In most cases, Python.NET can determine the correct constructor to -call automatically based on the arguments. In some cases, it may be necessary -to call a particular overloaded constructor, which is supported by a special -`__overloads__` attribute, which will soon be deprecated in favor of -iPy compatible "Overloads", on a class: - -```python -from System import String, Char, Int32 - -s = String.Overloads[Char, Int32]('A', 10) -s = String.__overloads__[Char, Int32]('A', 10) -``` - -## Using Generics - -Pythonnet also supports generic types. A generic type must be bound to -create a concrete type before it can be instantiated. Generic types support -the subscript syntax to create bound types: - -```python -from System.Collections.Generic import Dictionary -from System import * - -dict1 = Dictionary[String, String]() -dict2 = Dictionary[String, Int32]() -dict3 = Dictionary[String, Type]() -``` - -When you pass a list of types using the subscript syntax, you can also -pass a subset of Python types that directly correspond to .NET types: - -```python -dict1 = Dictionary[str, str]() -dict2 = Dictionary[str, int]() -dict3 = Dictionary[str, Decimal]() -``` - -This shorthand also works when explicitly selecting generic methods or -specific versions of overloaded methods and constructors (explained later). - -You can also subclass managed classes in Python, though members of the -Python subclass are not visible to .NET code. See the `helloform.py` file -in the `/demo` directory of the distribution for a simple Windows Forms -example that demonstrates subclassing a managed class. - -## Fields And Properties - -You can get and set fields and properties of CLR objects just as if they -were regular attributes: - -```python -from System import Environment - -name = Environment.MachineName -Environment.ExitCode = 1 -``` - -## Using Indexers - -If a managed object implements one or more indexers, you can call the -indexer using standard Python indexing syntax: - -```python -from System.Collections import Hashtable - -table = Hashtable() -table["key 1"] = "value 1" -``` - -Overloaded indexers are supported, using the same notation one would -use in C#: - -```python -items[0, 2] - -items[0, 2, 3] -``` - -## Using Methods - -Methods of CLR objects behave generally like normal Python methods. -Static methods may be called either through the class or through an -instance of the class. All public and protected methods of CLR objects -are accessible to Python: - -```python -from System import Environment - -drives = Environment.GetLogicalDrives() -``` - -It is also possible to call managed methods `unbound` -(passing the instance as the first argument) just as with Python methods. -This is most often used to explicitly call methods of a base class. - -**Note** There is one caveat related to calling unbound methods: it is -possible for a managed class to declare a static method and an instance -method with the same name. Since it is not possible for the runtime to know -the intent when such a method is called unbound, the static method will -always be called. - -The docstring of CLR a method (**doc**) can be used to view the signature -of the method, including overloads if the CLR method is overloaded. -You can also use the Python `help` method to inspect a managed class: - -```python -from System import Environment - -print(Environment.GetFolderPath.__doc__) - -help(Environment) -``` - -## Overloaded and Generic Methods - -While Python.NET will generally be able to figure out the right -version of an overloaded method to call automatically, there are cases -where it is desirable to select a particular method overload explicitly. - -Methods of CLR objects have an `__overloads__`, which will soon be -deprecated in favor of iPy compatible Overloads, attribute that can be -used for this purpose: - -```python -from System import Console - -Console.WriteLine.Overloads[bool](true) -Console.WriteLine.Overloads[str]("true") -Console.WriteLine.__overloads__[int](42) -``` - -Similarly, generic methods may be bound at runtime using the subscript -syntax directly on the method: - -```python -someobject.SomeGenericMethod[int](10) -someobject.SomeGenericMethod[str]("10") -``` - -## Out and Ref parameters - -When a managed method has `out` or `ref` parameters, the arguments appear as -normal arguments in Python, but the return value of the method is modified. -There are 3 cases: - -1. If the method is `void` and has one `out` or `ref` parameter, the method returns -the value of that parameter to Python. For example, if `someobject` has -a managed method with signature `void SomeMethod1(out arg)`, it is called like so: -``` -new_arg = someobject.SomeMethod1(arg) -``` -where the value of `arg` is ignored, but its type is used for overload resolution. - -2. If the method is `void` and has multiple `out`/`ref` parameters, the method returns -a tuple containing the `out`/`ref` parameter values. For example, if `someobject` has -a managed method with signature `void SomeMethod2(out arg, ref arg2)`, it is called like so: -``` -new_arg, new_arg2 = someobject.SomeMethod2(arg, arg2) -``` - -3. Otherwise, the method returns a tuple containing the return value followed by the -`out`/`ref` parameter values. For example: -``` -found, new_value = dictionary.TryGetValue(key, value) -``` - -## Delegates And Events - -Delegates defined in managed code can be implemented in Python. -A delegate type can be instantiated and passed a callable Python object -to get a delegate instance. The resulting delegate instance is a true -managed delegate that will invoke the given Python callable when it -is called: - -```python -def my_handler(source, args): - print('my_handler called!') - -# instantiate a delegate -d = AssemblyLoadEventHandler(my_handler) - -# use it as an event handler -AppDomain.CurrentDomain.AssemblyLoad += d -``` - -Delegates with `out` or `ref` parameters can be implemented in Python by -following the convention described in [Out and Ref parameters]. - -Multicast delegates can be implemented by adding more callable objects to -a delegate instance: - -```python -d += self.method1 -d += self.method2 -d() -``` - -Events are treated as first-class objects in Python, and behave in many -ways like methods. Python callbacks can be registered with event attributes, -and an event can be called to fire the event. -Note that events support a convenience spelling similar to that used in C#. -You do not need to pass an explicitly instantiated delegate instance to an -event (though you can if you want). Events support the `+=` and `-=` -operators in a way very similar to the C# idiom: +Python.NET is available as a source release on [GitHub][gh-release] and as a +single binary wheel distribution for all supported versions of Python and +from the [Python Package Index][pypi]. A [Nuget package][nuget] is provided +to embed Python into .NET. -```python -def handler(source, args): - print('my_handler called!') +## Documentation -# register event handler -object.SomeEvent += handler +Documentation for Python.NET is available here: +- [Documentation for Python.NET][doc] + - [Embedding .NET into Python][doc-py] + - [Embedding Python into .NET][doc-net] -# unregister event handler -object.SomeEvent -= handler - -# fire the event -result = object.SomeEvent(...) -``` - -## Exception Handling - -You can raise and catch managed exceptions just the same as you would -pure-Python exceptions: - -```python -from System import NullReferenceException - -try: - raise NullReferenceException("aiieee!") -except NullReferenceException as e: - print(e.Message) - print(e.Source) -``` - -## Using Arrays - -The type `System.Array` supports the subscript syntax in order to -make it easy to create managed arrays from Python: - -```python -from System import Array - -myarray = Array[int](10) -``` - -Managed arrays support the standard Python sequence protocols: - -```python -items = SomeObject.GetArray() - -# Get first item -v = items[0] -items[0] = v - -# Get last item -v = items[-1] -items[-1] = v - -# Get length -l = len(items) - -# Containment test -test = v in items -``` - -Multidimensional arrays support indexing using the same notation one -would use in C#: - -```python -items[0, 2] - -items[0, 2, 3] -``` - -## Using Collections - -Managed arrays and managed objects that implement the IEnumerable -interface can be iterated over using the standard iteration -Python idioms: - -```python -domain = System.AppDomain.CurrentDomain - -for item in domain.GetAssemblies(): - name = item.GetName() -``` - -## Using COM Components - -Using Microsoft-provided tools such as `aximp.exe` and `tlbimp.exe`, -it is possible to generate managed wrappers for COM libraries. After -generating such a wrapper, you can use the libraries from Python just -like any other managed code. - -Note: currently you need to put the generated wrappers in the GAC, in -the PythonNet assembly directory or on the PYTHONPATH in order to load them. - -## Type Conversion - -Type conversion under Python.NET is fairly straightforward - most -elemental Python types (string, int, long, etc.) convert automatically to -compatible managed equivalents (String, Int32, etc.) and vice-versa. -Note that all strings returned from the CLR are returned as unicode. - -Types that do not have a logical equivalent in Python are exposed as -instances of managed classes or structs (System.Decimal is an example). - -The .NET architecture makes a distinction between `value types` and -`reference types`. Reference types are allocated on the heap, and value -types are allocated either on the stack or in-line within an object. - -A process called `boxing` is used in .NET to allow code to treat a value -type as if it were a reference type. Boxing causes a separate copy of the -value type object to be created on the heap, which then has reference -type semantics. - -Understanding boxing and the distinction between value types and reference -types can be important when using Python.NET because the Python -language has no value type semantics or syntax - in Python -"everything is a reference". - -Here is a simple example that demonstrates an issue. If you are an -experienced C# programmer, you might write the following code: - -```python -items = System.Array.CreateInstance(Point, 3) -for i in range(3): - items[i] = Point(0, 0) - -items[0].X = 1 # won't work!! -``` - -While the spelling of `items[0].X = 1` is the same in C# and Python, -there is an important and subtle semantic difference. -In C# (and other compiled-to-IL languages), the compiler knows that -Point is a value type and can do the Right Thing here, changing the -value in place. - -In Python however, "everything's a reference", and there is really no -spelling or semantic to allow it to do the right thing dynamically. -The specific reason that `items[0]` itself doesn't change is that when -you say `items[0]`, that getitem operation creates a Python object that -holds a reference to the object at `items[0]` via a GCHandle. -That causes a ValueType (like Point) to be boxed, so the following -setattr (`.X = 1`) _changes the state of the boxed value, -not the original unboxed value_. - -The rule in Python is essentially: - -> the result of any attribute or item access is a boxed value - -and that can be important in how you approach your code. - -Because there are no value type semantics or syntax in Python, -you may need to modify your approach. To revisit the previous example, -we can ensure that the changes we want to make to an array item -aren't "lost" by resetting an array member after making changes to it: - -```python -items = System.Array.CreateInstance(Point, 3) -for i in range(3): - items[i] = Point(0, 0) - -# This _will_ work. We get 'item' as a boxed copy of the Point -# object actually stored in the array. After making our changes -# we re-set the array item to update the bits in the array. - -item = items[0] -item.X = 1 -items[0] = item -``` - -This is not unlike some of the cases you can find in C# where you have to -know about boxing behavior to avoid similar kinds of `lost update` problems -(generally because an implicit boxing happened that was not taken -into account in the code). - -This is the same thing, just the manifestation is a little different -in Python. See the .NET documentation for more details on boxing and the -differences between value types and reference types. - -## Embedding Python - -**Note:** because Python code running under Python.NET is inherently -unverifiable, it runs totally under the radar of the security infrastructure -of the CLR so you should restrict use of the Python assembly to trusted code. - -The Python runtime assembly defines a number of public classes that -provide a subset of the functionality provided by the Python C-API. - -These classes include PyObject, PyList, PyDict, PyTuple, etc. -You can review the nPython.exe source code in in "Console.csproj" project -for example of embedding CPython in console .NET app. Please refer to -this README GitHub page for new simplified embedding API: - -[README.rst][8] - -At a very high level, to embed Python in your application you will need to: - -- Reference Python.Runtime.dll in your build environment -- Call PythonEngine.Initialize() to initialize Python -- Call PythonEngine.ImportModule(name) to import a module - -The module you import can either start working with your managed app -environment at the time its imported, or you can explicitly lookup and -call objects in a module you import. - -For general-purpose information on embedding Python in applications, -use www.python.org or Google to find (C) examples. Because -Python.NET is so closely integrated with the managed environment, -you will generally be better off importing a module and deferring to -Python code as early as possible rather than writing a lot of managed -embedding code. - -**Important Note for embedders:** Python is not free-threaded and -uses a global interpreter lock to allow multi-threaded applications -to interact safely with the Python interpreter. -Much more information about this is available in the Python C-API -documentation on the www.python.org Website. - -When embedding Python in a managed application, you have to manage the -GIL in just the same way you would when embedding Python in -a C or C++ application. - -Before interacting with any of the objects or APIs provided by the -Python.Runtime namespace, calling code must have acquired the Python -global interpreter lock by calling the `PythonEngine.AcquireLock` method. -The only exception to this rule is the `PythonEngine.Initialize` method, -which may be called at startup without having acquired the GIL. - -When finished using Python APIs, managed code must call a corresponding -`PythonEngine.ReleaseLock` to release the GIL and allow other threads -to use Python. - -A `using` statement may be used to acquire and release the GIL: - -```csharp -using (Py.GIL()) -{ - PythonEngine.Exec("doStuff()"); -} -``` - -The AcquireLock and ReleaseLock methods are thin wrappers over the -unmanaged `PyGILState_Ensure` and `PyGILState_Release` functions from -the Python API, and the documentation for those APIs applies to -the managed versions. - -## Passing C# Objects to the Python Engine - -This section demonstrates how to pass a C# object to the Python runtime. -The example uses the following `Person` class: - -```csharp -public class Person -{ - public Person(string firstName, string lastName) - { - FirstName = firstName; - LastName = lastName; - } - - public string FirstName { get; set; } - public string LastName { get; set; } -} -``` - -In order to pass a C# object to the Python runtime, it must be converted to a -`PyObject`. This is done using the `ToPython()` extension method. The `PyObject` -may then be set as a variable in a `PyScope`. Code executed from the scope -will have access to the variable: - -```csharp -// create a person object -Person person = new Person("John", "Smith"); - -// acquire the GIL before using the Python interpreter -using (Py.GIL()) -{ - // create a Python scope - using (PyScope scope = Py.CreateScope()) - { - // convert the Person object to a PyObject - PyObject pyPerson = person.ToPython(); - - // create a Python variable "person" - scope.Set("person", pyPerson); - - // the person object may now be used in Python - string code = "fullName = person.FirstName + ' ' + person.LastName"; - scope.Exec(code); - } -} -``` +Documentation for the lower-level [`clr-loader`](cl) library is available here: +[Documentation for `clr-loader`][doc-cl] ## License Python.NET is released under the open source MIT License. A copy of the license is included in the distribution, -or you can find a copy of the [license online][9]. - -Some distributions of this package include a copy of the C Python dlls and -standard library, which are covered by the [Python license][10]. +or you can find a copy of the [license online][license]. ## .NET Foundation This project is supported by the [.NET Foundation](https://dotnetfoundation.org). -[1]: http://www.ironpython.com - -[2]: http://pythonnet.github.io/ +[ipy]: http://www.ironpython.com -[3]: https://mail.python.org/mailman3/lists/pythonnet.python.org/ +[ml]: https://mail.python.org/mailman3/lists/pythonnet.python.org/ -[4]: https://mail.python.org/archives/list/pythonnet@python.org/ +[ml-arch]: https://mail.python.org/archives/list/pythonnet@python.org/ -[5]: https://github.com/pythonnet/pythonnet/releases +[gh-release]: https://github.com/pythonnet/pythonnet/releases -[6]: https://pypi.python.org/pypi/pythonnet +[pypi]: https://pypi.python.org/pypi/pythonnet -[7]: http://www.go-mono.com +[nuget]: https://www.nuget.org/packages/pythonnet -[8]: https://github.com/pythonnet/pythonnet/blob/master/README.rst#embedding-python-in-net +[license]: https://pythonnet.github.io/LICENSE -[9]: http://pythonnet.github.io/LICENSE +[doc]: https://pythonnet.github.io/pythonnet/ -[10]: http://www.python.org/license.html +[doc-py]: https://pythonnet.github.io/pythonnet/python.html -[55]: http://github.com/pythonnet/pythonnet/issues +[doc-net]: https://pythonnet.github.io/pythonnet/dotnet.html -[77]: http://github.com/pythonnet/pythonnet +[doc-cl]: https://pythonnet.github.io/clr-loader/ -[78]: https://github.com/pythonnet/pythonnet/wiki/Installation +[gh-issues]: http://github.com/pythonnet/pythonnet/issues -[79]: https://github.com/pythonnet/pythonnet/wiki +[repo]: http://github.com/pythonnet/pythonnet From 803013226ffa0e050659d0c96ed93d00a979e718 Mon Sep 17 00:00:00 2001 From: Michael Wollensack <22192118+wollmich@users.noreply.github.com> Date: Fri, 18 Nov 2022 09:08:53 +0100 Subject: [PATCH 19/22] Python.NET is compatible with Python 3.7 - 3.11 (#21) Python.NET 3.0.1 supports Python 3.11, see https://pypi.org/project/pythonnet/3.0.1/ --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 683f0d4..17ef2c4 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ implementation of the Python language, you should check out the [IronPython][ipy] project, which is in active development. Python.NET is currently compatible and tested with Python releases -3.7 - 3.10. +3.7 - 3.11. To subscribe to the [Python.NET mailing list][ml] or read the [online archives][ml-arch] of the list, see the [mailing list information][ml] From f9505cfd0f4610e6ecc250f94cddaf4295b73653 Mon Sep 17 00:00:00 2001 From: Michael Wollensack <22192118+wollmich@users.noreply.github.com> Date: Fri, 18 Nov 2022 09:47:09 +0100 Subject: [PATCH 20/22] HTTP links replaced with HTTPS links (#22) --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 17ef2c4..7910c5b 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ or you can find a copy of the [license online][license]. This project is supported by the [.NET Foundation](https://dotnetfoundation.org). -[ipy]: http://www.ironpython.com +[ipy]: https://ironpython.net/ [ml]: https://mail.python.org/mailman3/lists/pythonnet.python.org/ @@ -79,6 +79,6 @@ This project is supported by the [.NET Foundation](https://dotnetfoundation.org) [doc-cl]: https://pythonnet.github.io/clr-loader/ -[gh-issues]: http://github.com/pythonnet/pythonnet/issues +[gh-issues]: https://github.com/pythonnet/pythonnet/issues -[repo]: http://github.com/pythonnet/pythonnet +[repo]: https://github.com/pythonnet/pythonnet From 847c0163965659f2c27294d5934f344000fda7bc Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Wed, 30 Oct 2024 21:29:32 +0100 Subject: [PATCH 21/22] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7910c5b..c2b2618 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ implementation of the Python language, you should check out the [IronPython][ipy] project, which is in active development. Python.NET is currently compatible and tested with Python releases -3.7 - 3.11. +3.7 - 3.12. To subscribe to the [Python.NET mailing list][ml] or read the [online archives][ml-arch] of the list, see the [mailing list information][ml] From 1720c529c2e73991f8825e1c3ae2db97048b76a6 Mon Sep 17 00:00:00 2001 From: Benedikt Reinartz Date: Fri, 13 Dec 2024 09:38:07 +0100 Subject: [PATCH 22/22] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c2b2618..9c60410 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ implementation of the Python language, you should check out the [IronPython][ipy] project, which is in active development. Python.NET is currently compatible and tested with Python releases -3.7 - 3.12. +3.7 - 3.13. To subscribe to the [Python.NET mailing list][ml] or read the [online archives][ml-arch] of the list, see the [mailing list information][ml]