Roshan r
Roshan r

Reputation: 522

How can i pass values from a C# form into Python

I am using Visual C# as UI and Python in the background.

  1. Enter the details on a visual C# form.
  2. Clicking a button should run a Python program which should embed the details given in the form into an XML file.
  3. Python should process the XML and ingest into a system.
  4. Python should monitor for the success from logs and return back the value to be displayed in C# form.

Is this possible?

Upvotes: 0

Views: 1520

Answers (1)

David Watts
David Watts

Reputation: 2289

You could start your python in a new process in the background and pass the form items as arguments in the process start information as if you were running the python script from the command line, like so:

var start = new ProcessStartInfo
            {
                FileName = _pathToPythonExecutable,
                Arguments = string.Format(" {0} --arg1 {1}",_pathToYourPythonScript, //formItemValue),
                UseShellExecute = false,
                RedirectStandardOutput = true,
                RedirectStandardInput = true,
                RedirectStandardError = true,
                WorkingDirectory = _currentWorkingDirectory            
            };
using (Process process = Process.Start(start))
            { 
                // Do stuff
            }

You'll see that in my start information, I have told the process to Redirect StandardInput, Standard Output and Standard Error. This is another way that you can pass data between the processes.

You would write to standard input like so:

process.StandardInput.Write(input);
process.StandardInput.Close();

Standard output and Standard Errors are streams, so you can read them like so

// This would be the same for standard error
using (StreamReader reader = process.StandardOutput)
                {
                    result = reader.ReadToEnd();
                }

Upvotes: 2

Related Questions