How to set the Anaconda virtual environment when working with IronPython?
Asked Answered
O

1

12

I want to run a python script in C# using IronPython. It works fine except IronPython is using my base Python installation instead of the Anaconda environment.

I've tried running the script with as an ordinary process (i.e without IronPython) and passing the script as an argument. This works but I loose the functionality of IronPython. E.g. ability to interrogate the Python variables.

I've also tried replacing the "Python" string with the location to the Python.exe in my anaconda environment and also the name of the Anaconda environment but it results in "unknown language" errors.

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());

The error message is related to the python library present in my anaconda environment doesn't exists in my base installation. (Ideally, I'd like to not have to install lots of libraries into my base.)

I expect the correct way is to pass the name of the Anaconda environment into the engine somehow but I haven't found it yet.

Thanks, Ian

Orianna answered 29/5, 2019 at 10:55 Comment(0)
T
0

Anaconda (in it's officially supported version) is for installing python packages for CPython (reference C implementation of python), often ones with binary dependencies such as pytorch or tensorflow. Packages for CPython won't work in IronPython (and many of them have no analogs) and Anaconda won't work with IronPython. Some packages for ironPython can be installed with pip, see here:

How to install packages/modules in IronPython

Now, getting to your actual problem you are trying to solve: "I've tried running the script with as an ordinary process (i.e without IronPython) and passing the script as an argument. This works but I loose the functionality of IronPython. E.g. ability to interrogate the Python variables."

Can't you just use debugger for CPython? That would allow you to inspect running program without need for migration to IronPython

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

Theater answered 22/9, 2022 at 21:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.