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);
    }
}
相关推荐
benjiangliu1 天前
LINUX系统-19-库制作与原理(一)
linux·运维·服务器
不如摸鱼去1 天前
Wot UI 2.3.0 发布:二维码组件来了,Open Wot 与 wot-starter 同步更新
前端·ui·微信小程序·前端框架·uni-app
玖石书1 天前
ASP.NET Core 迁移至 Spring系列:类库框架篇
java·后端·asp.net
Cloud_bread1 天前
从ReAct到自主闭环:Agentic Coding核心执行引擎的技术演进
前端·react.js·前端框架
cidy_981 天前
OptMem 使用教程
前端
摇滚侠1 天前
《SpringBoot 3:入门与应用实战》第 15 章 生产级特性 监控指标 Metrics 阅读笔记
java·spring boot·笔记
杉氧1 天前
用 Compose 挑战交互与动效天花板:ComposeCraftLab 开源实验室全解析
android·前端·kotlin
Canace1 天前
AI 生成到 90% 突然断了:你的解决方案是?
前端·人工智能
TinssonTai1 天前
Vite 8 版 Chrome 插件全家桶,popup/options/sidepanel 一次集齐
前端·vue.js
玉鸯1 天前
让 Agent 面向用户:AG-UI 协议构建 Agent 前端
前端·python·agent