使用 IronPython 时如何设置 Anaconda 虚拟环境?

Ian*_*let 9 c# python environment ironpython anaconda

我想使用 IronPython 在 C# 中运行 python 脚本。除了 IronPython 使用我的基础 Python 安装而不是 Anaconda 环境之外,它运行良好。

我尝试将脚本作为普通进程(即没有 IronPython)运行并将脚本作为参数传递。这有效,但我失去了 IronPython 的功能。例如,查询 Python 变量的能力。

我还尝试将“Python”字符串替换为 anaconda 环境中 Python.exe 的位置以及 Anaconda 环境的名称,但会导致“未知语言”错误。

var runtime = Python.CreateRuntime();
var engine = runtime.GetEngine("Python");   //I've tried replacing this with location of python.exe in the Ananconda environment but it fails

var script = "C:\\Documents\\my_pythonScript.py";
var source = engine.CreateScriptSourceFromFile(script);
var eIO = engine.Runtime.IO;

var results = new MemoryStream();
eIO.SetOutput(results, Encoding.Default);

var scope = engine.CreateScope();
source.Execute(scope);   

string str(byte[] x) => Encoding.Default.GetString(x);
string Results = str(results.ToArray());
Run Code Online (Sandbox Code Playgroud)

该错误消息与我的基本安装中不存在我的 anaconda 环境中存在的 python 库有关。(理想情况下,我不想在我的基础上安装很多库。)

我希望正确的方法是以某种方式将 Anaconda 环境的名称传递到引擎中,但我还没有找到它。

谢谢,伊恩

小智 0

Anaconda(在其官方支持的版本中)用于安装 CPython 的 python 包(Python 的参考 C 实现),通常具有二进制依赖项,例如 pytorch 或 tensorflow。CPython 的包无法在 IronPython 中工作(其中许多没有类似的包),并且 Anaconda 也无法与 IronPython 一起工作。一些ironPython的包可以用pip安装,请参见这里:

如何在 IronPython 中安装包/模块

现在,开始讨论您要解决的实际问题: “我尝试将脚本作为普通进程运行(即不使用 IronPython)并将脚本作为参数传递。这可行,但我失去了 IronPython 的功能。例如询问 Python 变量的能力。”

不能只使用 CPython 调试器吗?这将允许您检查正在运行的程序,而无需迁移到 IronPython

https://www.jetbrains.com/help/pycharm/part-1-debugging-python-code.html https://docs.python.org/3/library/pdb.html