using System;
using System.Diagnostics;
class Program
{
static void Main(string[] args)
{
// 创建一个 ProcessStartInfo 对象,用于设置启动 Python 脚本的参数
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "python"; // 指定 Python 解释器路径,默认为环境变量中配置的 Python
start.Arguments = @"script.py"; // 指定要执行的 Python 脚本文件路径
start.UseShellExecute = false; // 不使用操作系统 shell 启动
start.RedirectStandardOutput = true; // 重定向标准输出
start.RedirectStandardError = true; // 重定向标准错误
using (Process process = Process.Start(start))
{
using (System.IO.StreamReader reader = process.StandardOutput)
{
string result = reader.ReadToEnd(); // 读取 Python 脚本的输出结果
Console.WriteLine(result); // 打印输出结果到控制台
}
using (System.IO.StreamReader errorReader = process.StandardError)
{
string errors = errorReader.ReadToEnd(); // 读取 Python 脚本的错误信息
if (!string.IsNullOrEmpty(errors))
{
Console.WriteLine("Errors: " + errors); // 如果有错误信息,打印出来
}
}
}
}
}
UseShellExecute
设置为 false
表示不使用操作系统的 shell 启动进程,这样可以重定向标准输出和标准错误流,方便获取 Python 脚本的输出和错误信息。Process.Start(start)
启动 Python 脚本,并通过 StandardOutput
和 StandardError
流读取脚本的输出和错误信息。StreamReader
类读取 Python 脚本的标准输出和标准错误流,并将其打印到控制台。这个示例代码展示了如何在 C# 程序中调用 Python 脚本并处理其输出和错误信息。
上一篇:c#连接mysql
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站