Web开发:C#通过ProcessStartInfo动态调用执行Python脚本

一、代码思路

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);
    }
}
相关推荐
JavaGuide3 小时前
SpringBoot 官宣停止维护 3.2.x~3.4.x!
java·后端
无羡仙3 小时前
Vue插槽
前端·vue.js
tkevinjd3 小时前
动态代理
java
Knight_AL4 小时前
Spring 事务管理:为什么内部方法调用事务不生效以及如何解决
java·后端·spring
用户6387994773054 小时前
每组件(Per-Component)与集中式(Centralized)i18n
前端·javascript
SsunmdayKT4 小时前
React + Ts eslint配置
前端
开始学java4 小时前
useEffect 空依赖 + 定时器 = 闭包陷阱?count 永远停在 1 的坑我踩透了
前端
zerosrat4 小时前
从零实现 React Native(2): 跨平台支持
前端·react native
狗哥哥4 小时前
🔥 Vue 3 项目深度优化之旅:从 787KB 到极致性能
前端·vue.js