我能够创建 Python 脚本并通过 Visual Studio/.NET 4.0 动态运行它们,如下所示:
# testScript.py file:
import sys
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7.1\Lib')
import os
os.environ['HTTP_PROXY'] = "127.0.0.1:8888"
import urllib2
response = urllib2.urlopen("http://www.google.com")
然后在 .NET 4.0 WinForms 项目中:
ScriptEngine engine = Python.CreateEngine();
ScriptSource script = engine.CreateScriptSourceFromFile("testScript.py");
ScriptScope scope = engine.CreateScope();
script.Execute(scope);
但是,我导入的 IronPython DLL 不包含所有标准模块,所以我必须这样做
import sys
sys.path.append(r'C:\Program Files (x86)\IronPython 2.7.1\Lib')
一步,以便我可以运行接下来的 4 行。
有什么办法可以避免这种情况吗?
我要发布应用程序,我不想依赖每个人机器上的文件路径都相同!
最佳答案
有一个扩展方法可以让你直接这样做:
ScriptEngine engine = Python.CreateEngine();
ScriptSource script = engine.CreateScriptSourceFromFile("testScript.py");
ScriptScope scope = engine.CreateScope();
engine.SetSearchPaths(new string[] { "C:\\Program Files (x86)\\IronPython 2.7.1\\Lib" });
script.Execute(scope);
最好将 stdlib 与您的应用程序一起包含在私有(private)目录中,而不是依赖于它的安装,但这取决于您。
关于.net - 通过 Microsoft.Scripting 和 IronPython 运行 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9143689/