Search code examples
pythonpipenv

Pipenv and ModuleNotFoundError


I have spent hours looking into this issue without any success. I've looked at various SO discussions and none seem to solve my problem so out of pure frustration here is my question... I'm trying to launch a script within a windows batch file. The problem is that when I do the script fails because it can not find some of the modules used.

After various attempts I have found that the batch file aspect, at this stage, seems to be irrelevant.

So, ignoring batch files for a minute, If I run the script like this

pipenv run python myscript.py

It works. If I run the following it doesnt

path-to-env\Scripts\activate

python myscript.py

It returns an error ModuleNotFoundError: No module named 'xxx' It activates the venv OK, but something is not right as it cant find code used in script

Within my IDE (Visual Code) everything works OK

I do have quite a complicated directory structure but given that both the IDE and "pipenv run python myscript.py" work as expected it must be due to something else.

Any ideas or pointers on where I need to be looking? I'm afraid my understanding of pipenv isnt up to solving this ;)

EDIT

In my attempts to solve this I had added the line PYTHONPATH=. to my .env file. This seems to be responsible for allowing this line to work:

pipenv run python myscript.py

If I remove it, then the above ALSO generates the ModuleNotFoundError


Solution

  • OK so after trying lots of various combinations I did finally manage to get this to work. Although I have no idea why this solution works and others didnt..

    It requires two batch files.

    One to launch the python script which will contain a line like this

    python myscript.py

    And another to create the env via pipenv and then call the first batch file

    It will have a line like this

    pipenv run \path\to\first\batchfile.bat

    This combination works and can be successfully called from the Windows Task Scheduler