11

I'm trying to run a python script from unity (C# script) to use its output which is a text file in my game later, the thing is that when I run the C# script in unity nothing happens (Python script works fine on its own). Can anyone tell me what I'm missing? Thanks.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.IO;
using UnityEngine.UI;
using System.Text.RegularExpressions;
using System.Diagnostics;

using System.Runtime.InteropServices;
public class PyCx : MonoBehaviour {
    public Text Message;
    public GameObject OpenPanel1 = null;
    // Use this for initialization
    void Start () {
        python ();
        read ();
        ShowMessage ();
    }
    public void python(){
        ProcessStartInfo pythonInfo = new ProcessStartInfo ();
        Process python;
        pythonInfo.FileName=@"C:\Users\HP\AppData\Local\Programs\Python\Python36-32\python.exe";
        pythonInfo.Arguments=@"C:\Users\HP\Documents\projet1.pyw";
        pythonInfo.CreateNoWindow = false;
        pythonInfo.UseShellExecute = false;
        python = Process.Start (pythonInfo);
        python.WaitForExit ();
        python.Close ();
    }
    public void read(){
        using (var reader = new StreamReader ("C://Users//HP//Documents//result.txt")) {
            string line = reader.ReadToEnd ();
            Message.text = (line);
        }
    }
    public void ShowMessage(){
        OpenPanel1.SetActive (true);
        Message.IsActive ();
    }
    // Update is called once per frame
    void Update () {

    }
}

4 Answers 4

8

Instead of using a process which can be unreliable outside your controlled development environment (you don't know if your users will even have Python installed and which version) you could try to run Python directly in your code using IronPython, IronPython is a Python interpreter for the CLR so it doesn't even require Python to be installed to execute your scripts.

To use it you need to download the compiled binaries from http://ironpython.net/download/

Then copy all the required assemblies in your resources folder:

  • IronPython.dll
  • IronPython.Modules.dll
  • Microsoft.Scripting.Core.dll
  • Microsoft.Scripting.dll
  • Microsoft.Scripting.Debugging.dll
  • Microsoft.Scripting.ExtensionAttribute.dll
  • Microsoft.Dynamic.dll

Then you will have access to the Python Engine, you can initialize it as follows:

PythonEngine engine = new PythonEngine();  
engine.LoadAssembly(Assembly.GetAssembly(typeof(GameObject)));         
engine.ExecuteFile("Project1.py");

You can see more info here: http://ironpython.net/documentation/

References

http://shrigsoc.blogspot.com.es/2016/07/ironpython-and-unity.html https://forum.unity.com/threads/ironpython-in-unity-a-good-idea.225544/

Sign up to request clarification or add additional context in comments.

1 Comment

I can't get PythonEngine recognized in monodevelop!!
2
  • Download Unity Python package using the link Unity Python 0.4.1
  • Then, go to Edit > Project Settings > Player > Other Settings > Configuration and change Scripting Runtime Version to "Experimental (.NET 4.6 Equivalent)".

Assume you have a small code snippet test.py in Python like this:

class Test():
    def __init__(self, name):
        self.name = name
    def display(self):
        return "Hi, " + self.name

You can use it from C# like this

using System.Collections;
using System.Collections.Generic;
using IronPython.Hosting;
using UnityEngine;

public class PythonInterfacer : MonoBehaviour {
 void Start () {
        var engine = Python.CreateEngine();

        ICollection<string> searchPaths = engine.GetSearchPaths();

        //Path to the folder of greeter.py
        searchPaths.Add(@"C:\Users\Codemaker\Documents\PythonDemo\Assets\Scripts\Python\");
        //Path to the Python standard library
        searchPaths.Add(@"C:\Users\Codemaker\Documents\PythonDemo\Assets\Plugins\Lib\");
        engine.SetSearchPaths(searchPaths);

        dynamic py = engine.ExecuteFile(@"C:\Users\Codemaker\Documents\PythonDemo\Assets\Scripts\Python\test.py");
        dynamic obj = py.Test("Codemaker");
        Debug.Log(obj.display());
    }
}

Comments

0

Here is mine that works. Hope this helps.

var psi = new ProcessStartInfo();
// point to python virtual env
psi.FileName = @"C:\Users\someone\Documents\git-repos\PythonVenvs\venv\Scripts\python.exe";

// Provide arguments
var script = @"Assets\Scripts\somecoolpythonstuff\cool.py";
var vidFileIn = "111";
var inputPath = @"Assets\input";
var outputPath = @"Assets\output";

psi.Arguments = string.Format("\"{0}\" -v \"{1}\" -i \"{2}\" -o \"{3}\"", 
                               script, vidFileIn, inputPath, outputPath);

// Process configuration
psi.UseShellExecute = false;
psi.CreateNoWindow = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;

// Execute process and get output
var errors = "nothing";
var results = "nothing";

using (var process = Process.Start(psi))
{
    errors = process.StandardError.ReadToEnd();
    results = process.StandardOutput.ReadToEnd();
}

// grab errors and display them in UI
StringBuilder buffy = new StringBuilder();
buffy.Append("ERRORS:\n");
buffy.Append(errors);
buffy.Append("\n\n");
buffy.Append("Results:\n");
buffy.Append(results);

// ui text object
responseText.Text = buffy.ToString();

2 Comments

One problem here is that it assumes a Windows platform, and also a specific user name. If you want to port to Mac, Linux, or virtually any console, it may be an issue using a DOS-style path like that.
@Michael Macha The fix to the answer would be to use envrionment variables. Windows itself have the "Path" variable that may contain Python folder, which can help to reach Python without knowing its exact location. And Windows does support paths with /, not only \ .
0

You can try the following github repository code. You will get a basic idea of using python code in unity from a file

Unity Python Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.