首页 > 后端开发 > Python教程 > 如何在没有外部库的情况下从 C# 执行 Python 脚本?

如何在没有外部库的情况下从 C# 执行 Python 脚本?

Linda Hamilton
发布: 2024-12-07 09:57:12
原创
812 人浏览过

How Can I Execute Python Scripts from C# Without External Libraries?

从 C 运行 Python 脚本

许多开发人员都遇到了在 C# 应用程序中执行 Python 脚本的挑战。虽然存在 IronPython 等解决方案,但本文提供了一种简洁有效的方法来完成此任务,而无需使用外部库。

从 C# 运行 Python 脚本的关键是了解命令行执行的工作原理。当您从命令行执行命令时,您可以指定可执行文件(例如 python.exe),后跟脚本文件和任何必要的参数。

在 C# 中,您可以使用 ProcessStartInfo 类来指定命令-要执行的行。这是代码的更新版本,它正确地将 UseShellExecute 设置为 false 并使用 string.Format:

private void run_cmd(string cmd, string args)
{
     ProcessStartInfo start = new ProcessStartInfo();
     start.FileName = "my/full/path/to/python.exe";
     start.Arguments = string.Format("{0} {1}", cmd, args);
     start.UseShellExecute = false;
     start.RedirectStandardOutput = true;
     using(Process process = Process.Start(start))
     {
         using(StreamReader reader = process.StandardOutput)
         {
             string result = reader.ReadToEnd();
             Console.Write(result);
         }
     }
}
登录后复制

此代码确保使用 python.exe 的完整路径并正确格式化参数包含脚本文件名和要读取的文件。

以上是如何在没有外部库的情况下从 C# 执行 Python 脚本?的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板