从 C# 调用 python 代码(.py 文件)

发布于 2024-10-31 10:04:49 字数 99 浏览 0 评论 0原文

我有一些执行特定任务的 python 代码。我需要从 C# 调用此代码,而不将 python 文件转换为 .exe,因为整个应用程序是基于 C# 构建的。

我该怎么做?

I have some python code that does a certain task. I need to call this code from C# without converting the python file as an .exe, since the whole application is built on C#.

How can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心欲静而疯不止 2024-11-07 10:04:49

如果您的 python 代码可以通过 IronPython 执行,那么这绝对是最佳选择 - 它提供了最好的互操作性和意味着您将能够在脚本中使用.Net 对象。

从 C# 调用 IronPython 脚本的方法有很多,从将脚本编译为可执行文件到执行单个脚本文件或事件,在用户输入表达式时动态执行表达式 - 检查文档并发布另一个问题(如果您仍然不知道)有问题。

如果您的脚本是 CPython 脚本并且无法适应 IronPython,那么您的选择会更加有限。我相信存在一些 CPython / C# 互操作,但在快速 Google 搜索后我找不到它。我能想到的最好的办法是直接使用 python.exe 和 Process 类调用脚本。

If your python code can be executed via IronPython then this is definitely the way to go - it offers the best interop and means that you will be able to use .Net objects in your scripts.

There are many ways to invoke IronPython scripts from C# ranging from compiling the script up as an executable to executing a single script file or event dynamically executing expressions as they are typed in by the user - check the documentation and post another question if you are still haivng problems.

If your script is a CPython script and can't be adapted to work with IronPython then your options are more limited. I believe that some CPython / C# interop exists, but I couldn't find it after a quick Google search. The best thing I can think of would be to just invoke the script directly using python.exe and the Process class.

浅听莫相离 2024-11-07 10:04:49

看看 IronPython

根据您的回答和评论,我相信您能做的最好的事情就是将 IronPython 嵌入到您的应用程序中。与往常一样,有一个相关的问题。正如 Kragen 所说,重要的是不要依赖 CPython 模块。

Have a look at IronPython.

Based on your answer and comments, I believe that the best thing you can do is to embed IronPython in your application. As always, there is a relevant SO question about this. As Kragen said, it is important not to rely on a CPython module.

妞丶爷亲个 2024-11-07 10:04:49

Process.Start 就是您所追求的。它允许您调用另一个程序,并向其传递参数。

Process.Start is what you're after. It allows you to call another program, passing it arguments.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文