Search code examples
pythonpython-3.xpdbpython-venv

Can a Python script activate a virtual environment and then trigger an interactive pdb session within it?


On my Linux machine, I can activate the virtual environment and start an interactive debugging session with following bash commands -

source ~/pytorch-3.7-env/bin/activate
python -m pdb ~/python_project/testscript.py

Could a python script achieve the same?

The first command source ~/pytorch-3.7-env/bin/activate fails when I tried to execute it in a subshell possibly because source is a bash builtin -

>>> os.system("source pytorch-3.7-env/bin/activate")
sh: 1: source: not found
32512

any ideas?


Solution

  • It can but there's no reason to: you can just call the virtualenv's python directly (~/pytorch-3.7-env/bin/python) and it'll execute in the correct environment. You don't need to activate envs in a non-interactive environment.