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);
    }
}
相关推荐
兴趣互联1 小时前
jeecgboot nacos2.3.2 使用pgsql
java
H.莓飛1 小时前
【C++】【STL】stack_OJ题
服务器·c语言·开发语言·数据结构·c++·算法·visual studio
hudd6681 小时前
JavaEE 初阶 - 文件操作和IO
java·开发语言·java-ee
JavaGuide2 小时前
Cloudflare 开源的这套神级安全审计 Skill 太好用了!
前端·后端
Flynn Liang2 小时前
HikariCP 连接池不是越大越好:I/O 密集型 Java 服务的数据库容量工程
java·数据库·mysql·高并发·连接池·hikaricp·sql 优化
学长毕设2 小时前
基于SpringBoot社区快递驿站物流配送系统-附源码
java·spring boot·后端
Flynt3 小时前
Java4Shell 实测:EPYC 一跑就中招,关掉 Base64 硬件加速,1KB 解码慢 14 倍
java·安全·性能优化
Resean02233 小时前
Spring 源码分析(七)AOP 原理(上):代理的创建
java·后端·spring
孟健3 小时前
用 unslop 拯救 AI 生成网页的塑料感,7 分钟重构落地实测
前端·人工智能·ai编程
Tangq一定可以的3 小时前
Spring AI Advisor 详解 - 给大模型调用加上“切面“,日志/过滤/记忆一键搞定
java·后端·spring