0

I have not found easy to understand answers on how venv can be loaded from a python .py script.

I currently have my python libraries installed via PIP on a venv. Wish CONDA could be used but it is not the case (see PS:)

To run a script from the Command window (Windows 10) I will do:

c:\myEnvFolder\Scripts\activate.bat
python.exe myScript.py

This works fine, I can also do the following to run Spyder and then load any of myEnvFolder libraries

c:\myEnvFolder\Scripts\activate.bat
Spyder

Problem comes when trying to use xlwings. As python is called from excel it points to the stock Python install and does not include myEnvFolder libraries.

I tried adding this to main.py that xlwings runs:

import sys
import os
home = os.path.expanduser("~")
sys.path = sys.path[:-1]        # Remove default lib path
sys.path.append(home + '\\Dev')
sys.path.append(home + '\\Dev\\lib\\site-packages')
sys.path.append(home + '\\Dev\\lib\\site-packages\win32')
sys.path.append(home + '\\Dev\\lib\\site-packages\win32\lib')
sys.path.append(home + '\\Dev\\lib\\site-packages\Pythonwin')

But I then get a error when doing import xlwings :

ImportError: DLL load failed while importing _win32sysloader: The specified module could not be found.

So basically I need to either:

  1. Add more info to my current path amending so it replicates what activate.bat does or

  2. Somehow run activate.bat (or similar) when main.py is called

Thank!

PS: With CONDA this was trivial. You just pointed to the python.exe on the ENV you wanted to use. With PIP and venv this is not possible

PS2:

I have tried the following: Activate a virtualenv with a Python script

So I create the activate_this.py file and then run:

import os
home = os.path.expanduser("~")

activate_this_file = home + '\\Dev\\Scripts\\activate_this.py'

exec(compile(open(activate_this_file, "rb").read(), activate_this_file, 'exec'), dict(__file__=activate_this_file))

When I try to do import xlwins I get once again:

ImportError: DLL load failed while importing _win32sysloader: The specified module could not be found.
Yona
  • 571
  • 7
  • 23
  • https://stackoverflow.com/questions/6943208/activate-a-virtualenv-with-a-python-script – rasjani Aug 19 '22 at 09:46
  • @rasjani I get the same error message `ImportError: DLL ...` I created the `activate_this.py` file and then executed: `exec(compile(open(activate_this_file, "rb").read(), activate_this_file, 'exec'), dict(__file__=activate_this_file))` – Yona Aug 19 '22 at 10:25

0 Answers0