docs.unity3d.com
    Show / Hide Table of Contents

    Use Python APIs in C#

    Use Python APIs in C# with Python for .NET.

    Requirements and syntax

    Before writing your Python code, you have to:

    1. Ensure that Python is initialized with PythonRunner.EnsureInitialized().

    2. Grab the CPython Global Interpreter Lock (GIL).

    Note

    Using Py.GIL requires a reference to the Python.Runtime assembly: create a new assembly reference in Unity and set the Assembly Definition property to com.unity.scripting.python.editor.

    In practice, the code structure in C# must look like this:

    PythonRunner.EnsureInitialized();
    using (Py.GIL())
    {
        ...
        your code goes here
        ...
    }
    

    Example: log the current Python version in the Console

    Code

    The following C#/Python code creates a menu item that logs the current Python version in the Unity Console.

    using Python.Runtime;
    using UnityEditor;
    using UnityEditor.Scripting.Python;
    
    public class MyPythonScript
    {
        [MenuItem("MyPythonScripts/Log Python Version")]
        public static void LogPythonVersion()
        {
            PythonRunner.EnsureInitialized();
            using (Py.GIL())
            {
                try
                {
                    dynamic sys = Py.Import("sys");
                    UnityEngine.Debug.Log($"python version: {sys.version}");
                }
                catch(PythonException e)
                {
                    UnityEngine.Debug.LogException(e);
                }
            }
        }
    }
    

    Test

    From the main menu of the Editor, select MyPythonScripts > Log Python Version.

    The Python version currently used in your project should appear in the Unity Console.

    Additional references

    • Call Python instructions from C#
    • Call Python script files from C#
    Back to top
    Copyright © 2023 Unity Technologies — Terms of use
    • Legal
    • Privacy Policy
    • Cookies
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)
    "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
    Generated by DocFX on 18 October 2023