How can I get IronPython in C# to run a script that requires an active VENV? Is this possible?

80 Views Asked by At

I've installed IronPython 3.4 (https://github.com/IronLanguages/ironpython3/releases/tag/v3.4.1) and I'm trying to run several font-related python scripts that depend upon an active VENV (FontTools, ftCLI, and some other packages).

Is this even possible? I have been doing some research on IronPython, but nothing mentions virtual environments.

Is it possible to accomplish what I need? Is there another solution that will run a script in an active VENV using C#?

Thank you for any guidance.

1

There are 1 best solutions below

0
Ben On

In summary, you need to pass the full path to the venv version of Python.

A venv consists of:

  • A directory e.g. /home/bob/dev/project/.venv or C:/Users/Bob/dev/project/.venv which contains the the things which constitute the venv.
    • a local repository where python modules are installed
    • a directory of scripts, which are stubs for launching Python, Pip, etc. (e.g. bin for Linux)
    • a script called activate which modifies the environment of the current shell so that those scripts are called first, and so that Python will look in site-packages first.

If called from a shell, such as Bash, Zsh, Powershell or Cmd, the activate script will modify the environment of the shell, so that when you type python, the version of python is the venv python. You "activate" the venv with either call .venv/Scripts/activate.cmd for windows, or source .venv/bin/activate for Linux.

However if you just want to ensure that the python module or file is run in the venv, all you have to do is specify the full path the venv python stub.

E.g. on Windows:


var psi = new System.Diagnostics.ProcessStartInfo(
    @"C:\Users\Bob\dev\project\.venv\Scripts\Python.exe"
  ){
    ArgumentList = {
      "-m",
      "@C:\Users\Bob\dev\project\main_module.py" // add other arguments as needed
    }
}
proc = Process.Start(psi);

So how does this work?

The .exe files in .venv\Scripts (Windows) or .venv/bin (Linux) are small executables which check their own names and directory to discover the correct venv location, and python version. They then launch the real Python, Pip etc, with the correct environment.

The situation on Linux etc is very similar, except that the directories are named differently, e.g. .venv/bin instead of .venv/scripts.