从 C# 调用 python 代码(.py 文件)
我有一些执行特定任务的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的 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 theProcess
class.看看 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.
Process.Start 就是您所追求的。它允许您调用另一个程序,并向其传递参数。
Process.Start is what you're after. It allows you to call another program, passing it arguments.