Warning
Because Python code running under Python.NET is inherentlyunverifiable, it runs totally under the radar of the securityinfrastructure of the CLR so you should restrict use of the Pythonassembly to trusted code.
The Python runtime assembly defines a number of public classes thatprovide a subset of the functionality provided by the Python C-API.
These classes include PyObject, PyList, PyDict, PyTuple, etc.
At a very high level, to embed Python in your application one will needto:
ReferencePython.Runtime.dll
(e.g. via aPackageReference
)
CallPythonEngine.Initialize()
to initialize Python
Callvarmod=PyModule.Import(name)
to import a module asmod
The module you import can either start working with your managed appenvironment at the time its imported, or you can explicitly lookup andcall objects in a module you import.
For general-purpose information on embedding Python in applications, usewww.python.org or Google to find (C) examples. Because Python.NET is soclosely integrated with the managed environment, one will generally bebetter off importing a module and deferring to Python code as early aspossible rather than writing a lot of managed embedding code.
Note
Python is not free-threaded and uses aglobal interpreter lock to allow multi-threaded applications to interactsafely with the Python interpreter. Much more information about this isavailable in the Python C-API documentation on the www.python.orgWebsite.
When embedding Python in a managed application, one has to manage theGIL 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 thePython.Runtime
namespace, calling code must have acquired the Pythonglobal interpreter lock byusing''``Py.GIL()
. The only exception tothis rule is thePythonEngine.Initialize
method, which may be calledat startup without having acquired the GIL. The GIL is released againby disposing the return value ofPy.GIL():
using(Py.GIL()){PythonEngine.Exec("doStuff()");}// or{usingvar_=Py.GIL()PythonEngine.Exec("doStuff()");}// orvargil=Py.GIL();try{PythonEngine.Exec("doStuff()");}finally{gil.Dispose();}
ThePy.GIL()''objectisathinwrapperovertheunmanaged``PyGILState_Ensure
(on construction) andPyGILState_Release
(ondisposal) functions from the Python API, and the documentation for thoseAPIs applies to the managed versions.
This section demonstrates how to pass a C# object to the Python runtime.The example uses the followingPerson
class:
publicclassPerson{publicPerson(stringfirstName,stringlastName){FirstName=firstName;LastName=lastName;}publicstringFirstName{get;set;}publicstringLastName{get;set;}}
In order to pass a C# object to the Python runtime, it must be convertedto aPyObject
. This is done using theToPython()
extensionmethod. ThePyObject
may then be set as a variable in aPyScope
.Code executed from the scope will have access to the variable:
// create a person objectPersonperson=newPerson("John","Smith");// acquire the GIL before using the Python interpreterusing(Py.GIL()){// create a Python scopeusing(PyModulescope=Py.CreateScope()){// convert the Person object to a PyObjectPyObjectpyPerson=person.ToPython();// create a Python variable "person"scope.Set("person",pyPerson);// the person object may now be used in Pythonstringcode="fullName = person.FirstName + ' ' + person.LastName";scope.Exec(code);}}