24 Contributors: 1 Wednesday, July 12, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial:
Roadmap: roadmap

Call Python from C#


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


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( )
     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();

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.

Related Examples