Reputation: 103
In my virtual environment on my debian machine, I am able to import numpy at the prompt But when I call it in a program it errors out.
I am looking over the net and they say to uninstall and re-install. I tried but novail. Also, I am able to import it in python prompt but not when I call the script? Please help me out of this.
I am able to call successfully at the prompt:-
(venv) root@c3-redsuren-vm01:~/my-project# python
Python 3.8.2 (default, Apr 13 2020, 08:44:45)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> import numpy
>>> exit()
Here when I try to execute my program it errors out:-
(venv) root@c3-redsuren-vm01:~/my-project# ./test_nump.py
Traceback (most recent call last):
File "./test_nump.py", line 2, in <module>
import numpy
ImportError: No module named numpy
(venv) root@c3-redsuren-vm01:~/my-project# cat test_nump.py
#!/usr/bin/python
import numpy
print("test")
(venv) root@c3-redsuren-vm01:~/my-project#
Upvotes: 2
Views: 234
Reputation: 792
As per request from the OP.
For any executable file, bash reads the first line with the shebang
or #!...
to extract the interpreter for the script. If it does not find the shebang, it will try to service the file type using the magic numbers and then use the relevant loading method. That's why running an ELF binary does not require you to specify the executor.
Now, virtual environments works by overriding your bash search path, i.e. when you type a command, where should it look. For example, if you have a binary name ls
where should it find it to load from. It refers to your search path or the $PATH
variable and scans the directories sequentially and stops at the first match. Virtual environment will prepend it's path to the $PATH
when you do a source .venv
. The source
command simply tells your bash session to apply the bash directives from the .venv
file.
In your source file, you have supplied the interpreter using the shebang
directive to the global installation of python which does not have numpy
in it's module list so it fails.
If you run it using python script.py
, because the $PATH
is overridden by virtual env, the shell will find the python version of virtual env first than the global one which has your numpy module.
Why does /usr/bin/env python
work ? Because it's going to refer to your $PATH
in your environment variable (which is modified by virtual env) and will find the correct python installation.
Upvotes: 2