I am trying to retrieve a list of installed kernels in a virtual environment from within a Python script that runs in a different virtual environment. Usually, in the console, I use jupyter kernelspec list from the virtual environment that I am interested in. But I don't get this to work within a Python script.
What I tried:
import subprocess
from pathlib import Path
env1 = Path(r'C:\virtualenvs\my_env\Scripts\python.exe')
env2 = Path(r'C:\virtualenvs\jupyter_env\Scripts\python.exe')
jupyter1 = Path(r'C:\virtualenvs\my_env\Scripts\jupyter.exe')
jupyter2 = Path(r'C:\virtualenvs\jupyter_env\Scripts\jupyter.exe')
packages1 = subprocess.run([env1, '-m', 'pip', 'list'],
stdout=subprocess. PIPE)
print(packages1.stdout.decode('utf-8'))
packages2 = subprocess.run([env2, '-m', 'pip', 'list'],
stdout=subprocess. PIPE)
print(packages2.stdout.decode('utf-8'))
kernels1 = subprocess.run([jupyter1, 'kernelspec', 'list'],
stdout=subprocess. PIPE)
print(kernels1.stdout.decode('utf-8'))
kernels2 = subprocess.run([jupyter2, 'kernelspec', 'list'],
stdout=subprocess. PIPE)
print(kernels2.stdout.decode('utf-8'))
I execute this script from within my_env. The result is:
Package Version
----------------------------- ---------
asteval 0.9.27
...
zipp 3.8.1
Package Version
-------------------- -----------
anyio 3.6.1
...
websocket-client 1.3.3
Available kernels:
python3 C:\virtualenvs\my_env\share\jupyter\kernels\python3
Available kernels:
python3 C:\virtualenvs\my_env\share\jupyter\kernels\python3
The calls pip list give me the result from the respective environments irrespective of the environment that runs the script. However, the kernelspec calls show the kernels of the environment I am executing from (my_env) in both cases.
Question A: How can I make sure the last of the subprocess calls is executed within the jupyter_env?
or
Question B: How can I get the list of kernels from a specific virtual environment from a Python script (maybe there is a solution that does not involve subprocess calls)?
I'm using Python 3.10.3 and jupyter-core 4.11.1 in both environments.