How to run a project with a specific virtual environment

Hi,
i have 2 projects with their own virtual environment. the ide is visual studio. OS is win11
c:\dir1\main1.py
c:\dir2\main2.py
running within VS the code runs without issues.
within cmd i run
py c:\dir1\main1.py
this will fire py.exe from the global environment according to the path settings.
in main1.py i have a
from bs4 import BeautifulSoup
bs4 is in the VE but not in the GE. So i get an error that bs4 is not found.

main1.py and main2.py is called from excel-VBA with shell()
So i can i run main1 and main2 ?

Thanks in advance

Well, this may be complicated. I know nothing about VBA, but I suspect shell() doesn’t store a state so you can’t switch to an venv and execute your script in one line. :frowning:

There are 2 ideas that came into my mind right now:

  • Install BeautifulSoup in GE too, or
  • Make an small .bat or PowerShell script, where you put all necessary commands to set up the venv and run your python script, and call that file from your shell()

thanks for the quick reply
With shell() i can run a batchfile
my batchfile so far:
(path)\python.exe -m venv c:\dir1\VirtualEnvironmentSFM
(path)\python.exe c:\dir1\main1.py
i get : ModuleNotFoundError: No module named ‘bs4’
what should the batchfile look like?

This creates a new venv everytime it is called. You rather need to run an activation code from your venv. I’m not sure if this is the same on Windows, but when I create a new venv I need to cd bin/ and run activate from there (on Windows probably there is an equivalent .bat script for this).

You should not need to cd to source activate AIUI. But better, you
don’t even need to source the activate script, which is a convenience
thing for people’s sheels. I never use it.

Instead, it is enough to use the python command from inside the venv
to run the script. Example:

 /path/to/venv/bin/python your_script.py

will run the script using a Python which uses the venv.

I haven’t tried any of this on Windows, but I expect it to be the same.
So I’d expect a batch file which went:

 c:\dir1\VirtualEnvironmentSFM\bin\python c:\dir1\main1.py

should do the trick just fine, after the OP has installed bs4 into
the venv.

2 Likes

Cameron,
Thank you. That works!!