Class PythonRunner | Python for Unity | 2.0.1-preview.2
docs.unity3d.com
    Show / Hide Table of Contents

    Class PythonRunner

    This class encapsulates methods to run Python strings, files and clients inside of Unity.

    Inheritance
    Object
    PythonRunner
    Namespace: UnityEditor.Scripting.Python
    Syntax
    public static class PythonRunner

    Fields

    PythonRequiredVersion

    The Python version we require.

    Changing this to 3 isn't going to magically make it work, the constant is just to help find some parts that matter.

    Declaration
    public const string PythonRequiredVersion = "2.7"
    Field Value
    Type Description
    String

    Properties

    InProcessPythonVersion

    The version of the in-process Python interpreter.

    Declaration
    public static string InProcessPythonVersion { get; }
    Property Value
    Type Description
    String

    A string representing the version.

    Methods

    CallAsyncServiceOnClient(String, String, Object[])

    Method to use with C# async/await semantics. Call this if the client is expected to call back the server. If the call to this method is not awaited, the execution of this method will continue on its own.

    Declaration
    public static Task<dynamic> CallAsyncServiceOnClient(string clientName, string serviceName, params object[] args)
    Parameters
    Type Name Description
    String clientName

    name of the client to make the call to.

    String serviceName

    name of the service to be called.

    Object[] args

    the arguments to be passed on to the called service.

    Returns
    Type Description
    Task<Object>

    The task that is the asynchronous call to the service. Wait for it to finish with Task.wait() or discard the return value if none is expected.

    CallCoroutineServiceOnClient(String, String, Object[])

    Convenience function to call a method on a client, asynchronously. Call this if the client is expected to call back the server.

    Use as a coroutine in a GameObject: StartCoroutine(PythonRunner.CallCoroutineServiceOnClient("foo", "bar"))

    Or iterate over the enumerator in a Unity coroutine: var pycall = PythonRunner.CallCoroutineServiceOnClient("foo", "bar"); while (pycall.MoveNext()) { yield return null; /* throws here if the result arrives and is an error / } / do something with pycall.Current if we care about the return value */

    This is a wrapper around unity_python.server.server.call_service_on_client_async. If you want keyword arguments, call the Python directly with:

      dynamic server_module = PythonEngine.ImportModule(&quot;unity_python.server.server&quot;);
      return server_module.call_service_on_client_async(clientName, 0, serviceName, args, kwargs);
    

    Where args is a tuple or list and kwargs is a dict.

    Declaration
    public static IEnumerator CallCoroutineServiceOnClient(string clientName, string serviceName, params object[] args)
    Parameters
    Type Name Description
    String clientName

    The name of the client to call the service on.

    String serviceName

    The name of the service to call.

    Object[] args

    Arguments to be passed to the service. Must be basic types (strings, int, bool) or PyObject.

    Returns
    Type Description
    IEnumerator

    An IEnumerator.

    CallServiceOnClient(String, String, Object[])

    Convenience function to call a service on a client.

    This is a wrapper around unity_python.server.server.call_service_on_client. If you want keyword arguments, call the Python directly with:

      dynamic server_module = PythonEngine.ImportModule(&quot;unity_python.server.server&quot;);
      return server_module.call_service_on_client(clientName, 0, serviceName, args, kwargs);
    

    Where args is a tuple or list and kwargs is a dict.

    Declaration
    public static dynamic CallServiceOnClient(string clientName, string serviceName, params object[] args)
    Parameters
    Type Name Description
    String clientName

    The name of the client to call the service on.

    String serviceName

    The name of the service to call.

    Object[] args

    Arguments to be passed to the service. Must be basic types (strings, int, bool) or PyObject.

    Returns
    Type Description
    Object

    Null if the service returns None (or has no explicit return), else a PyObject.

    CloseClient(String, Boolean)

    Closes or reset a client by calling the "on_server_shutdown" service.

    Declaration
    public static void CloseClient(string clientName, bool inviteRetry = false)
    Parameters
    Type Name Description
    String clientName

    The name of the client to close or reset.

    Boolean inviteRetry

    If true, send on_server_shutdown(true). If false, send on_server_shutdown(false)

    EnsureInProcessInitialized()

    Ensures the in-process Python API is initialized.

    Safe to call frequently.

    Throws if there's an installation error.

    Declaration
    public static void EnsureInProcessInitialized()

    EnsureOutOfProcessInitialized()

    Ensures the out of process API is initialized.

    Safe to call frequently.

    Throws if there's an installation error.

    Declaration
    public static void EnsureOutOfProcessInitialized()

    ForceRestart()

    Reinitialize the server e.g. after a crash.

    This is not idempotent.

    It will close the server, delete the socket file, then start the server again.

    Does not throw exceptions (but logs them).

    Declaration
    public static void ForceRestart()

    GetConnectedClients()

    Returns the names of the connected clients. If there are multiple instances of a client, returns only one copy of the name.

    Declaration
    public static string[] GetConnectedClients()
    Returns
    Type Description
    String[]

    An array of string that contains the connected clients.

    GetRPyCVersion()

    Returns the version of RPyC currently in use.

    Declaration
    public static string GetRPyCVersion()
    Returns
    Type Description
    String

    A human-readable string representing the version of RPyC.

    GetSocketPath()

    Return the path to the socket file.

    Declaration
    public static string GetSocketPath()
    Returns
    Type Description
    String

    IsClientConnected(String)

    Tests if a client is connected to the server.

    Declaration
    public static bool IsClientConnected(string clientName)
    Parameters
    Type Name Description
    String clientName

    The name of the client.

    Returns
    Type Description
    Boolean

    True if the client is connected, False otherwise.

    NumClientsConnected()

    Returns the total number of clients connected to the server.

    Declaration
    public static int NumClientsConnected()
    Returns
    Type Description
    Int32

    NumClientsConnected(String)

    Returns the number of clients of the same name connected to the server.

    Declaration
    public static int NumClientsConnected(string clientName)
    Parameters
    Type Name Description
    String clientName

    The name of the client.

    Returns
    Type Description
    Int32

    The number of clients connected.

    RunFile(String)

    Runs a Python script in the Unity process.

    Declaration
    public static void RunFile(string pythonFileToExecute)
    Parameters
    Type Name Description
    String pythonFileToExecute

    The script to execute.

    RunString(String)

    Runs Python code in the Unity process.

    Declaration
    public static void RunString(string pythonCodeToExecute)
    Parameters
    Type Name Description
    String pythonCodeToExecute

    The code to execute.

    SpawnClient(String, Boolean, String[])

    Spawns a new client by launching a new Python interpreter and having it execute the file.

    Returns immediately after spawning the new Python process. If you need Unity to coordinate with the client, you will need to wait for the client to connect to the Unity server. If the client script fails to run, check the logs to see exactly what was executed and try to run the script by hand in a shell terminal to find the errors.

    The Python interpreter chosen is the one in the Python Settings.

    Declaration
    public static dynamic SpawnClient(string file, bool wantLogging = true, params string[] arguments)
    Parameters
    Type Name Description
    String file

    The file to be executed.

    Boolean wantLogging

    If true, turns on debug logging for the Python client startup. If false, silences all messages and errors during startup.

    String[] arguments

    The arguments to be passed to the script.

    Returns
    Type Description
    Object

    The Popen Python object that is the newly spawned client.

    StartServer()

    Starts the Python server and the job-processing loop. Calling this is idempotent: if the server has already started, this call has no effect.

    Declaration
    public static void StartServer()

    StopServer(Boolean)

    Stops the Python server and the job processing loop. Calling this is idempotent: if the server is already closed, this call has no effect.

    Declaration
    public static void StopServer(bool inviteReconnect)
    Parameters
    Type Name Description
    Boolean inviteReconnect

    If true, signal the clients the server will be restarted.

    WaitForConnection(String, Double)

    Waits at most timeout seconds for a client to be connected. To be used as a Unity coroutine.

    Declaration
    public static IEnumerator WaitForConnection(string clientName, double timeout = 10)
    Parameters
    Type Name Description
    String clientName

    The name of the client to wait for.

    Double timeout

    The maximum time to wait on the client, in seconds.

    Returns
    Type Description
    IEnumerator

    The IEnumerator to iterate upon. Always yields null.

    In This Article
    • Fields
      • PythonRequiredVersion
    • Properties
      • InProcessPythonVersion
    • Methods
      • CallAsyncServiceOnClient(String, String, Object[])
      • CallCoroutineServiceOnClient(String, String, Object[])
      • CallServiceOnClient(String, String, Object[])
      • CloseClient(String, Boolean)
      • EnsureInProcessInitialized()
      • EnsureOutOfProcessInitialized()
      • ForceRestart()
      • GetConnectedClients()
      • GetRPyCVersion()
      • GetSocketPath()
      • IsClientConnected(String)
      • NumClientsConnected()
      • NumClientsConnected(String)
      • RunFile(String)
      • RunString(String)
      • SpawnClient(String, Boolean, String[])
      • StartServer()
      • StopServer(Boolean)
      • WaitForConnection(String, Double)
    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