在C#中执行python脚本 [英] execute a python script in C#
问题描述
我正在尝试在C#中执行python代码.通常,应该使用IronPython并在安装PTVS之后完成此操作(我使用的是VS 2010).
I am trying to execute a python code in C#. Normally it should be done using IronPython and after installing PTVS (I'm using VS 2010).
var pyEngine = Python.CreateEngine();
var pyScope = pyEngine.CreateScope();
try
{
pyEngine.ExecuteFile("plot.py", pyScope);
}
catch (Exception ex)
{
Console.WriteLine("There is a problem in your Python code: " + ex.Message);
}
问题是,IronPython似乎无法识别某些库,例如numpy,pylab或matplotlib.我看了一下,发现有些人在谈论Enthought Canopy或Anaconda,但我都安装了它们却没有解决问题. 我该怎么做才能解决问题?
The problem is that it seems that IronPython doesn't recognize some libraries like numpy, pylab or matplotlib. I took a look a little bit and found some people talking about Enthought Canopy or Anaconda, which i have both installed without fixing the problem. What should I do to get the problem solved?
推荐答案
为了执行导入某些库(例如numpy和pylab)的Python脚本,可以这样做:
In order to execute a Python script which imports some libraries such as numpy and pylab, it is possible to make this:
string arg = string.Format(@"C:\Users\ayed\Desktop\IronPythonExamples\RunExternalScript\plot.py"); // Path to the Python code
Process p = new Process();
p.StartInfo = new ProcessStartInfo(@"D:\WinPython\WinPython-64bit-2.7.5.3\python-2.7.5.amd64\python.exe", arg);
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true; // Hide the command line window
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.RedirectStandardError = false;
Process processChild = Process.Start(p.StartInfo);
这篇关于在C#中执行python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!