1

I need help understanding venv and project management on a Windows 7 system.

I have installed Python 3.7.4. Running the command 'pip list' results in the following:

Package     Version
pip         19.0.3
setuptools  40.8.0

Under the path C:\Projects\NeuralNetworks I have the following files/folders:

project_env #virtual environment created with venv
main.py

When activating my virtual environment 'project_env\Scripts\activate.bat' the command 'pip list' results in:

Package     Version
numpy       1.16.4
pip         19.0.3
setuptools  40.8.0

When I go to run main.py I get the error "NameError: name 'numpy' is not defined".

#main.py
import numpy as np

print(numpy.version.version)
input('Press enter to continue...')

I expect to see the version of numpy but instead I get the error that numpy is not found which tells me I don't really understand how these directories work.

Solution: I added runserver.bat to my project directory with following.

CALL C:\Projects\NeuralNetworks\project_env\Scripts\activate.bat
python C:\Projects\NeuralNetworks\main.py runserver

I run the runserver.bat and everything works perfectly.

Riskinit
  • 97
  • 2
  • 8
  • Add the full error please – developer_hatch Jul 24 '19 at 20:24
  • How are you running main.py? From the command-line or by double-clicking the file? – Michael Kolber Jul 24 '19 at 20:24
  • I would like to be able to double click the file but the window just opens and closes immediately. When I run the file from the cmd.exe I get 'NameError: name 'numpy' is not defined. – Riskinit Jul 24 '19 at 20:31
  • 1
    You have to activate the venv in the same console you run the script. – Christian K. Jul 24 '19 at 20:32
  • Ok, after activating it and changing print(numpy.version.version) to print(np.version.version) I was able to get the result I wanted. That leaves the question of can I just double click the file and get the same result? – Riskinit Jul 24 '19 at 20:37

1 Answers1

1

You need to create a .bat file where you added some code inside to activate the environment first and then run your python file.

something like :

@echo off
cmd /k "cd /d ..\env\Scripts & activate & cd /d    ..\foldername & python main.py

Reference : A Python script that activates the virtualenv and then runs another Python script?

J.K
  • 1,178
  • 10
  • 13