Run Python scripts synchronously from C #

Introduction

So far I've written some similar stories about how C # and Python work together.

In "Run Python script from C # GUI application", Python script is executed and the progress can be checked until the process is completed.

In "Run Python code from C # GUI", I tried to make it possible to input Python code from the screen instead of the Python script.

And in "Run and manage processes in the background from C # GUI", after executing Python, do another work without waiting for the end. At the same time, I investigated how to check the execution status when I was interested.

Therefore, this is the last story in this series.

** In the first place, I want to create a method that executes a Python script and receives the processing result from a GUI, but what do you do? ** **

In short, it is a call that starts a Python script without going through the GUI, waits there (synchronizes) without going to the next process until the execution is completed, and then gets the result.

Source

Yes, don't.

PythonExecutor.cs


using System;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace ChemShow
{
    public class PythonExecutor
    {
        public String FileName { get; set; }
        public String WorkingDirectory { get; set; }
        public String Arguments { get; set; }
        public String InputString { get; set; }
        public String StandardOutput { get; set; }
        public int ExitCode { get; set; }

        private StringBuilder standardOutputStringBuilder = new StringBuilder();

        public PythonExecutor()
        {

        }

        ///Behavior when the execute button is clicked
        public  void Execute()
        {
            
            ProcessStartInfo psInfo = new ProcessStartInfo();
            psInfo.FileName = this.FileName;
            psInfo.WorkingDirectory = this.WorkingDirectory;
            psInfo.Arguments = this.Arguments;

            psInfo.CreateNoWindow = true;
            psInfo.UseShellExecute = false;
            psInfo.RedirectStandardInput = true;
            psInfo.RedirectStandardOutput = true;
            psInfo.RedirectStandardError = true;

            // Process p = Process.Start(psInfo);
            Process p = new System.Diagnostics.Process();
            p.StartInfo = psInfo;
            p.OutputDataReceived += p_OutputDataReceived;
            p.ErrorDataReceived += p_ErrorDataReceived;

            //Process execution
            p.Start();

            //Write to standard input
            using (StreamWriter sw = p.StandardInput)
            {
                sw.Write(InputString);
            }

            //Start reading output and error asynchronously
            p.BeginOutputReadLine();
            p.BeginErrorReadLine();

            //Wait till the end
            p.WaitForExit();
            this.ExitCode = p.ExitCode;
            this.StandardOutput = standardOutputStringBuilder.ToString();
        }

        /// <summary>
        ///Processing when standard output data is received
        /// </summary>
        void p_OutputDataReceived(object sender,
            System.Diagnostics.DataReceivedEventArgs e)
        {
            //processMessage(sender, e);
            if (e != null && e.Data != null && e.Data.Length > 0)
            {
                standardOutputStringBuilder.Append(e.Data + "\n");
            }
        }

        /// <summary>
        ///What to do when a standard error is received
        /// </summary>
        void p_ErrorDataReceived(object sender,
            System.Diagnostics.DataReceivedEventArgs e)
        {
            //Write the necessary processing
        }
    }
}

Source commentary

There's nothing new, just start the process and just run `WaitForExit ()`. Then you won't be able to continue until the process is finished. As a result, synchronous calling can be realized. After the execution is completed, the exit code and standard output data can be obtained from the properties.

How to use

The following is an example of giving data to the standard input of a script and receiving the result output to the standard output.

PythonExecutor pe = new PythonExecutor();
pe.FileName=@"c:\python3.6\bin\python.exe";
pe.WorkingDirectory = @"c:\tmp";
pe.Arguments =@"C:\ChemShow\python\hist.py";
pe.InputString = "1,2,3,4,5,6,7,8,9,10"; //Data given to standard input
pe.Execute(); //Run
Console.WriteLine(pe.StandardOutput); //Output standard output result

2020/2/24 revised

Fixed as follows because there was a fatal bug that started the process twice. We apologize for the inconvenience.

// Process p = Process.Start(psInfo); Process p = new System.Diagnostics.Process(); p.StartInfo = psInfo;

in conclusion

In short, it's a story of making a component that corresponds to all the calling methods that have come out so far.

Later, the title is a Python script, but it's the same if it can be executed from the command line.

Recommended Posts

Run Python scripts synchronously from C #
Run Python Scripts from Cisco Memorandum_EEM
Run a Python script from a C # GUI application
Run illustrator script from python
Call C from Python with DragonFFI
Call popcount from Ruby / Python / C #
Run Aprili from Python with Orange
Tips for calling Python from C
Execute Python code from C # GUI
Run Ansible from Python using API
Check installed modules from Python scripts
Call C / C ++ from Python on Mac
Call c language from python (python.h)
Generate C language from S-expressions in Python
Use C ++ functions from python with pybind11
Run Python in C ++ on Visual Studio 2017
sql from python
python C ++ notes
python, openFrameworks (c ++)
MeCab from Python
Create a C array from a Python> Excel sheet
Run Python YOLOv3 in C ++ on Visual Studio 2017
Wrap C with Cython for use from Python
Call a Python script from Embedded Python in C ++ / C ++
Run a Python file from html using Django
Wrap C ++ with Cython for use from Python
I want to make C ++ code from Python code!
Run a python script from excel (using xlwings)
Notes on oct2py calling Octave scripts from Python
Use thingsspeak from python
Run Python from Excel VBA with xlwings & tutorial supplement
Run Python with VBA
Operate Filemaker from Python
Use fluentd from python
Run prepDE.py with python3
Python C / C ++ Extension Pattern-Pointer
Access bitcoind from python
Changes from Python 3.0 to Python 3.5
Python from or import
Use MySQL from Python
Install python from source
Execute command from Python
Python points from the perspective of a C programmer
Next Python in C
Run Blender with python
Operate neutron from Python!
Use MySQL from Python
Import classes in jar files directly from Python scripts
Operate LXC from Python
Manipulate riak from python
Use BigQuery from python.
C API in Python 3
Run BigQuery from Lambda
ABC147 C --HonestOrUnkind2 [Python]
Execute command from python
Cloud Run tutorial (python)
Quickly profile Python scripts
[Python] How to call a c function from python (ctypes)
[Python] Read From Stdin
Run iphone safari from mac with python + selenium + safari-webdriver
Use mecab-ipadic-neologd from python