Calling python code(.py files) from C#

大城市里の小女人 提交于 2019-12-18 04:53:17

问题


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?


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/5591557/calling-python-code-py-files-from-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!