一、代码思路
1.定义要传递的整数和字符串。
2.创建临时 Python 脚本内容。
3.将脚本写入临时文件。
4.配置并启动 Python 进程。
5.输出结果并删除临时文件。
二、代码
cs
using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
int numberToPass = 5; // 要传递的整数
string stringToPass = "Hello"; // 要传递的字符串
// 创建一个临时 Python 脚本
string tempFilePath = Guid.NewGuid().ToString() + ".py";
string pythonCode = @"
import sys
def process_data(num, text):
num += 1
print(f'Number: {num}, String: {text}')
if __name__ == '__main__':
# 从命令行参数获取数据
num = int(sys.argv[1])
text = sys.argv[2]
process_data(num, text)";
// 写入临时文件
System.IO.File.WriteAllText(tempFilePath, pythonCode);
// 设置进程信息
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = @"D:\Python\python.exe"; // Python 解释器路径
start.Arguments = $"{tempFilePath} {numberToPass} \"{stringToPass}\""; // 传递参数
start.UseShellExecute = false; // 不使用操作系统外壳启动
start.RedirectStandardOutput = true; // 重定向标准输出
start.RedirectStandardError = true; // 重定向标准错误
using (Process process = Process.Start(start))
{
// 获取输出
string result = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
// 输出结果
if (!string.IsNullOrEmpty(result))
{
Console.WriteLine("Output: " + result);
}
if (!string.IsNullOrEmpty(error))
{
Console.WriteLine("Error: " + error);
}
}
// 删除临时文件
System.IO.File.Delete(tempFilePath);
}
}