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

Section 188.1: 被 C# 应用程序调用的 Python 脚本

import sys
import json

# 从文本文件中加载输入参数
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']]
print(json.dumps({'sum': x + y, 'subtract': x - y}))

Section 188.2: 调用 Python 脚本的 C# 代码

第 188 章:从 C# 调用 Python
文档提供了一个 C# 和 Python 脚本之间进程间通信的示例实现。
第 188.1 节:被 C# 应用程序调用的 Python 脚本
Python复制
import sys
import json

# 从文本文件中加载输入参数
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']]
print(json.dumps({'sum': x + y, 'subtract': x - y}))
第 188.2 节:调用 Python 脚本的 C# 代码
csharp复制
using MongoDB.Bson;
using System;
using System.Diagnostics;
using System.IO;

namespace python_csharp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Python 脚本的完整路径
            string pyScriptPath = "...../sum.py";
            // 将输入参数转换为 JSON 字符串
            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;
            // 创建新的进程启动信息
            ProcessStartInfo prcStartInfo = new ProcessStartInfo
            {
                // Python 解释器的完整路径 'python.exe'
                FileName = "python.exe",
                UseShellExecute = false,
                RedirectStandardOutput = true,
                CreateNoWindow = false
            };

            try
            {
                // 将输入参数写入 .txt 文件
                using (StreamWriter sw = new StreamWriter(argsFile))
                {
                    sw.WriteLine(argsBson);
                    prcStartInfo.Arguments = string.Format("{0} {1}", string.Format(@"""{0}""", pyScriptPath), string.Format(@"""{0}""", argsFile));
                }
                // 启动进程
                using (Process process = Process.Start(prcStartInfo))
                {
                    // 读取标准输出中的 JSON 字符串
                    using (StreamReader myStreamReader = process.StandardOutput)
                    {
                        outputString = myStreamReader.ReadLine();
                        process.WaitForExit();
                    }
                }
            }
            finally
            {
                // 删除/保存临时 .txt 文件
                if (!saveInputFile)
                {
                    File.Delete(argsFile);
                }
            }
            Console.WriteLine(outputString);
        }
    }
}