Python Language Call Python from C#

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Introduction

The documentation provides a sample implementation of the inter-process communication between C# and Python scripts.

Remarks

Note that in the example above data is serialized using MongoDB.Bson library that can be installed via NuGet manager.

Otherwise, you can use any JSON serialization library of your choice.


Below are inter-process communication implementation steps:

  • Input arguments are serialized into JSON string and saved in a temporary text file:

     BsonDocument argsBson = BsonDocument.Parse("{ 'x' : '1', 'y' : '2' }"); 
     string argsFile = string.Format("{0}\\{1}.txt", Path.GetDirectoryName(pyScriptPath), Guid.NewGuid());
    
  • Python interpreter python.exe runs the python script that reads JSON string from a temporary text file and backs-out input arguments:

     filename = sys.argv[ 1 ]
     with open( filename ) as data_file:  
        input_args = json.loads( data_file.read() )
    
     x, y = [ float(input_args.get( key )) for key in [ 'x', 'y' ] ]
    
  • Python script is executed and output dictionary is serialized into JSON string and printed to the command window:

     print json.dumps( { 'sum' : x + y , 'subtract' : x - y } )
    

    enter image description here

  • Read output JSON string from C# application:

     using (StreamReader myStreamReader = process.StandardOutput)
     {
        outputString = myStreamReader.ReadLine();
        process.WaitForExit();
     }
    

enter image description here

I am using the inter-process communication between C# and Python scripts in one of my projects that allows calling Python scripts directly from Excel spreadsheets.

The project utilizes ExcelDNA add-in for C# - Excel binding.

The source-code is stored in the GitHub repository.

Below are links to wiki pages that provide an overview of the project and help to get started in 4 easy steps.

I hope you find the example and the project useful.




Got any Python Language Question?