I'm attempting to understand how to execute a Python script file from a C# program. I'm using Python 3.10 and Visual Studio 2022 for my C# program.
Since this appears to be a very popular question here, I looked at quite a few other posts & responses regarding this. However, I'm still not quite understand what the proper way to do this, as I'm struggling to call even a basic script with a single supplied argument.
I understand that there is a method for doing this using the IronPython library, however I must find a way do this without installing any additional libraries.
The most common other way I found across these posts is to use the Process
in-built library.
I have a test Python script named test.py
, which I placed in the root folder of my C# program, which simply prints out the single argument supplied to the script:
import sys
if (__name__ == '__main__'):
print(sys.argv[1])
The closest I've been able to get is the following C# code from this StackOverflow post:
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "C:\\Program Files\\Python310\\python.exe";
start.Arguments = string.Format("{0} {1}", "test.py", "a");
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd();
OutputConsole.AppendText(result + Environment.NewLine);
}
}
Execution of the code above results in the result
string local variable always being null
. Another thing I also noticed is that the script doesn't give me any sort of error message or prompt if I move the test.py
script file somewhere else.
In the StackOverflow post above, one of the answers mentions the fact that if the UseShellExecute
field of the start
local variable is set to false
, then I must always supply the full path to my Python interpreter EXE file as the first argument of the Arguments
field of the start
variable.
What am I doing wrong here? Is there another way of doing this without using additional libraries?
Thanks for reading my post, any guidance is appreciated.