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);
    }
}
相关推荐
咖啡八杯12 小时前
GoF设计模式——工厂方法模式
java·后端·设计模式
Yupureki12 小时前
《MySQL数据库基础》6.表的增删查改
linux·服务器·数据库·mysql
CDN36013 小时前
【硬核架构】2026年服务器运维:Rust重写核心组件与eBPF内核观测的实战
运维·服务器·架构
代码羊羊13 小时前
Rust 迭代器完全通俗易懂指南(零基础全覆盖)
java·开发语言·rust
MY_TEUCK20 小时前
【Java 后端】SpringBoot 登录认证与会话跟踪实战(JWT + Filter/Interceptor)
java·开发语言·spring boot
镜宇秋霖丶20 小时前
2026.5.6@霖宇博客制作中遇见的问题
前端·javascript·vue.js
今天长肉了吗20 小时前
银行风控项目踩坑实录:指标跑了6小时,风险评分全挂了
java
Yupureki21 小时前
《Linux网络编程》8.网络层IP原理
linux·运维·服务器·网络·ip
大厂数码评测员21 小时前
免费菜谱管理小程序怎么做才顺手:从情侣、个人、家庭三类场景拆需求和实现
服务器·小程序·apache
随读手机21 小时前
多式联运信息交互平台完整方案(2026版)
java·ai·eclipse·云计算·区块链