'C# Process.Start() not starting despite file existing and setting working directory
I'm trying to use a C# script in Unity to call a python program. After following these two links:
How do I run a Python script from C#?
Process.Start() not starting the .exe file (works when run manually)
I could not get my C# script to call the python program. I know this isn't a problem with my python script because I can run the program in terminal without a problem.
public class JsonStream : MonoBehaviour
{
private string GetStream()
{
ProcessStartInfo start = new ProcessStartInfo();
//none of the paths work, the uncommented variables return true when using File.Exists
//while the commented variables return false
start.FileName = "/Library/Frameworks/Python.framework/Versions/3.6/bin/python3";
//start.FileName = "\"/Library/Frameworks/Python.framework/Versions/3.6/bin/python3\"";
start.Arguments = Directory.GetCurrentDirectory() + "/Assets/googlesheetspyprojectbatch/stream.py";
//start.Arguments = "\"" + Directory.GetCurrentDirectory() + "/Assets/googlesheetspyprojectbatch/stream.py" + "\"";
start.WorkingDirectory = Directory.GetCurrentDirectory() + "/Assets/googlesheetspyprojectbatch";
//start.WorkingDirectory = "\"" + Directory.GetCurrentDirectory() + "/Assets/googlesheetspyprojectbatch" + "\"";
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.ErrorDialog = true;
start.RedirectStandardError = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
return result;
}
}
}
public void DoEverythingStream()
{
UnityEngine.Debug.Log("Doing Stream");
string json_text = GetStream();
string[] games = json_text.Trim().Split('\n');
foreach (string game in games)
{
UnityEngine.Debug.Log(game);
}
}
}
Running the program raises no errors but also doesn't output anything. Does anyone have any ideas what may be wrong with my program? Thanks!
Solution 1:[1]
Old question, but I was struggling to figure out why C# (Unity) wasn't running my Python file even though a manual command prompt could.
By putting my python script's path in triple double quotes ("""), C# was able to run the script.
Example:
string fileName = @"""PATH\TO\YOUR\SCRIPT.PY""";
string pythonPath = @"PATH\TO\PYTHON.EXE";
System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = new System.Diagnostics.ProcessStartInfo(pythonPath, fileName)
{
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
p.Start();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sludge |