如何从C#程序调用Python程序

该文档提供了C#和Python脚本之间的进程间通信的示例实现。

从C#调用Python:由C#应用程序调用的Python脚本

import sys
import json
load input arguments from the text file filename = sys.argv[ 1 ]
with open( filename ) as data_file: input_args = json.loads( data_file.read() )
cast strings to floats
x, y = [ float(input_args.get( key )) for key in [ 'x', 'y' ] ]
print json.dumps( { 'sum' : x + y , 'subtract' : x - y } )

C#代码调用Python脚本

using MongoDB.Bson;
using System;
using System.Diagnostics;
using System.IO;
namespace python_csharp
{
class Program
{
static void Main(string[] args)
{
//full path to .py file
string pyScriptPath = "…../sum.py";
//convert input arguments to JSON string
BsonDocument argsBson = BsonDocument.Parse("{ 'x' : '1', 'y' : '2' }");
bool saveInputFile = false;
string argsFile = string.Format("{0}\{1}.txt", Path.GetDirectoryName(pyScriptPath), Guid.NewGuid());
string outputString = null;
//create new process start info
ProcessStartInfo prcStartInfo = new ProcessStartInfo
{
//full path of the Python interpreter 'python.exe'
FileName = "python.exe", //string.Format(@"""{0}""", "python.exe"),
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = false
};
try
{
//write input arguments to .txt file
using (StreamWriter sw = new StreamWriter(argsFile))
{
sw.WriteLine(argsBson);
prcStartInfo.Arguments = string.Format("{0} {1}", string.Format(@"""{0}""", pyScriptPath), string.Format(@"""{0}""", argsFile));
}
//start process
using (Process process = Process.Start(prcStartInfo))
{
//read standard output JSON string
using (StreamReader myStreamReader = process.StandardOutput)
{
outputString = myStreamReader.ReadLine();
process.WaitForExit();
}
}
}
finally
{
delete/save temporary .txt file if (!saveInputFile)
{
File.Delete(argsFile);
}
}
Console.WriteLine(outputString);
}
}
}
日期:2020-06-02 22:16:02 来源:oir作者:oir