无法在Visual Studio中使用IronPython运行python脚本
我曾尝试在Visual Studio中使用IronPython运行python脚本,并且它很顺利,直到我尝试使用此代码在python脚本中使用任何库时。无法在Visual Studio中使用IronPython运行python脚本
var ipy = Python.CreateRuntime();
dynamic test = ipy.UseFile("C:/Python/Test.py");
var whatever = test.python_string();
MessageBox.Show(whatever);
而Test.py看起来像这样。
def python_string():
return "Okay"
当我尝试添加
from moviepy.editor import *
或任何其他libary import语句的Python代码在Visual Studio程序将不会执行。
我使用的是Visual Studio 2015,并且我完全按照他们的网站所示设置了IronPython。我猜我必须将库添加到Visual Studio中的某个地方,但我不知道在哪里或如何。
希望我明确表示。提前致谢。
当我遇到这个问题时,在另一个地方有另一个类似性质的问题,但我现在没有任何运气。 (如果有人遇到它,请在评论中删除链接。)
我得到它的工作方式是通过向脚本引擎添加路径,就像这样。
ScriptRuntimeSetup setup = Python.CreateRuntimeSetup(null);
ScriptRuntime runtime = new ScriptRuntime(setup);
ScriptEngine engine = Python.GetEngine(runtime);
var paths = engine.GetSearchPaths();
paths.Add(prod.GetImportScope());
paths.Add(AppDomain.CurrentDomain.BaseDirectory + "Lib");
paths.Add(AppDomain.CurrentDomain.BaseDirectory + "selenium");
engine.SetSearchPaths(paths);
当您在IronPython中运行脚本时,它不会运行在Python文件通常的范围内。所以你必须告诉它在哪里可以找到你正在导入的Python StdLib和其他文件。即使脚本自行运行,它也不会在IronPython中告诉它在哪里找到它的资源。
我不是IronPython的专家,所以可能有更高效的方法来做到这一点。
我在使用SharpDevelop时遇到了同样的问题。请按照说明here并为您的外部模块/软件包创建类库(DLL)。将输出的DLL添加到您的项目引用。然后在你的C#的main(),加载这些组件是这样的:
// make sure to include "using System.IO"
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "serial.dll");
engine.Runtime.LoadAssembly(Assembly.LoadFile(path));
凡engine
指的是你的Python ScriptEngine
。
我用它来构建pyserial
模块的程序集,并将它们包含在C#/ IronPython项目中。我不知道是否有更好的方法,但经过几个小时的挫折后,这对我来说是有效的。
[在Visual Studio中使用带有库的python文件](http://stackoverflow.com/questions/39862954/using-python-files-with-libraries-in-visual-studio) – denfromufa