Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hy i want to communicated the between c# and python interpreter


So i want to send the command through c# and Excecute the command in python .


The problem I want to run
Execute 2 python commands consecutively

but not working in current .


So could you help me out how to Run the 2 or more process run
consecutively


What I have tried:

PythonManager Testprocess = new PythonManager();

var pythonCommand1 = "a = 4; print(\"Expected a = 4. Actual a = {} \".format(a))";
            var pythonCommand2 = "b=2;print(\"Expected b = 2. Actual b = {} \".format(b));print(\"Expected a = 4. Actual a = \");print(a)";
            Console.WriteLine(Testprocess.ExecuteCommand(pythonCommand1));
            Console.WriteLine(Testprocess.ExecuteCommand(pythonCommand2));
            Console.ReadLine();




<pre>public string ExecuteCommand(string command)
        {
            // KIlling and restarting the process is not right. Need to resolve.

            try
            {
                if (!_pythonProcess.HasExited)
                {
                    _pythonProcess.Kill();
                }
                _pythonProcess.StartInfo.Arguments = string.Format("");
                _pythonProcess.Start();
                //_pythonProcess.StandardInput.AutoFlush = true;
                _pythonProcess.StandardInput.WriteLine(command);
                _pythonProcess.StandardInput.Flush();
                //_pythonProcess.StandardInput.Dispose();
                _pythonProcess.StandardInput.Close();
                _pythonProcess.WaitForExit();
                var outputString = _pythonProcess.StandardOutput.ReadToEnd();
                return outputString;
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.ToString());
                return null;
            }
        }
Posted
Updated 11-Aug-22 6:13am
Comments
Richard MacCutchan 1-Aug-22 9:44am    
That is not valid input to the Python interpreter. It needs to read each statement on a separate line, and also requires correct indentation. It would be better to create a .py file from the C# code and pass the filename to the Python invocation.
HelpMewithCode 1-Aug-22 10:50am    
Console.WriteLine("Expected result = 6. Actual result = " + testProcess.RunScript("\"C:main\\test\\Test.py\" pro 2 3"));
Console.ReadLine()


I have tried what you have mentioned but it will run one process at a time ..

could you help me out this please

1 solution

If I correctly understood you want to run the 2 commands in order, first
var pythonCommand1 = "a = 4; print(\"Expected a = 4. Actual a = {} \".format(a))";

and then
var pythonCommand2 = "b=2;print(\"Expected b = 2. Actual b = {} \".format(b));print(\"Expected a = 4. Actual a = \");print(a)";

If this is the case the resulting output will be
Expected a = 4. Actual a = 4 
Expected b = 2. Actual b = 2 
Expected a = 4. Actual a = 
4

You could create a single Python script
a = 4
print("Expected a = 4. Actual a = {} ".format(a))

b=2
print("Expected b = 2. Actual b = {} ".format(b))
print("Expected a = 4. Actual a = ")
print(a)

and then run it from your C# application
using System.Diagnostics;

string pyScript = "script.py";    // If you don't have the script in the same folder you have to include the full path to it
string pyScriptResult = string.Empty;

using (Process proc = new Process())
{
    proc.StartInfo.FileName = "python3";
    proc.StartInfo.Arguments = pyScript;
    proc.StartInfo.UseShellExecute = false;
    proc.StartInfo.CreateNoWindow = true;
    proc.StartInfo.RedirectStandardOutput = true;

    proc.Start();
    proc.WaitForExit();
    pyScriptResult = proc.StandardOutput.ReadToEnd();
}

Console.WriteLine(pyScriptResult);

And you'll get the exact same output
dotnet run                                                                                           
Expected a = 4. Actual a = 4 
Expected b = 2. Actual b = 2 
Expected a = 4. Actual a = 
4
 
Share this answer
 
Comments
HelpMewithCode 12-Aug-22 0:56am    
Thank you so much CySalazar.
i need to pass argument through python script

my script.py
import sys

def prod(args):
if (len(args) == 0):
return 0
product = 1
for arg in args:
product *= arg
return product

if __name__ == "__main__":
if (len(sys.argv) < 2):
print(f"USAGE: {sys.argv[0]} cmd [args]")
sys.exit(1)
cmd = sys.argv[1]
args= (int(sys.argv[2]),int(sys.argv[3])) if (len(sys.argv) > 2) else []
if cmd == "sum":
print(sum(args))
elif cmd == "prod":
print(prod(args))
else:
print("cmd can be sum or prod.")
sys.exit(1)



program.cs

Console.WriteLine("Expected result = 6. Actual result = " + xrayprocess.RunScript("\"C:\\script.py\" prod 2 3"));
//Console.ReadLine();

//Execute 2 python commands consecutively
var pythonCommand1 = "a = 4; print(\"Expected a = 4. Actual a = {} \".format(a))";
var pythonCommand2 = "b=2;print(\"Expected b = 2. Actual b = {} \".format(b));print(\"Expected a = 4. Actual a = \");print(a)";
Console.WriteLine(xrayprocess.ExecuteCommand(pythonCommand1));
Console.WriteLine(xrayprocess.ExecuteCommand(pythonCommand2));
}



RunScript.py
public string RunScript(string script)
{
try
{
if (!_pythonProcess.HasExited)
{
_pythonProcess.Kill();
}
_pythonProcess.StartInfo.Arguments = string.Format("{0}", script);
_pythonProcess.Start();
var outputString = _pythonProcess.StandardOutput.ReadToEnd();
return outputString;
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
return null;
}
}


with above the code i want to run multiple command with one processs

Exact same output which mentioned but using above script
@CySalazar i hope u will help me on this
CySalazar 12-Aug-22 3:22am    
You can always add the arguments you want to pass to the Python script to process.arguments like this

string pyScript = "script.py arg1 arg2";

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900