I want to run a Python script from C#. This has been working fine, following the approach shown here
I am retrieving the values using argv inside the python script The issue arises, when I try to pass float values to my python application. I'm not sure whether argv can't separate the floating point number properly or why they don't seem to arrive.
My Code: C#:
using System;
using System.IO;
using System.Diagnostics;
namespace CallPython
{
class ProgramIntercom
{
static void Main(string[] args)
{
// full path of python interpreter
string python = @"C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\python.exe";
// python app to call
string myPythonApp = "TestIntercom.py";
// parameters to send to the Python script
float num1 = 1;
float num2 = 1.6125f;
float num3 = 2;
float num4 = 0.2f;
float num5 = -2;
float num6 = 0.9046666667f;
// Create new process start info
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);
// make sure we can read the output from stdout
myProcessStartInfo.UseShellExecute = false;
myProcessStartInfo.RedirectStandardOutput = true;
myProcessStartInfo.CreateNoWindow = true;
// start python app with 7 arguments
// 1st arguments is pointer to itself,
// the next 6 are actual arguments we want to send (Python needs to filter out the first one)
myProcessStartInfo.Arguments = myPythonApp + " " + num1 + " " + num2 + " " + num3 + " " + num4 + " " + num5 + " " + num6;
Process myProcess = new Process();
// assign start information to the process
myProcess.StartInfo = myProcessStartInfo;
Console.WriteLine("Calling Python script with arguments: {0}, {1}, {2}, {3}, {4}, {5} ", num1, num2, num3, num4, num5, num6);
// start the process
myProcess.Start();
// Read the standard output of the app we called.
// in order to avoid deadlock we will read output first
// and then wait for process terminate:
StreamReader myStreamReader = myProcess.StandardOutput;
string result = myStreamReader.ReadToEnd();
/*if you need to read multiple lines, you might use:
string myString = myStreamReader.ReadToEnd() */
// wait exit signal from the app we called and then close it.
myProcess.WaitForExit();
myProcess.Close();
// write the output we got from python app
Console.WriteLine("Value received from script: " + result);
}
}
}
The Example Python Script:
from sys import argv
# Get the arguments from the command line
python_path, num1, num2 , num3, num4, num5, num6 = argv
# sum up the two numbers
sum = float(num1) + float(num2) + float(num3) + float(num4) + float(num5) + float(num6)
# print the sum
print(sum)
When using floats instead of integers no result is printed out in the C# application