简体   繁体   中英

In a virtual env the sys.path is wrong when I import a package from a file

The sys.path change only if I import a package from another file.

In my pyenv :

$(env) python
>>> import sys
>>> print(sys.path)
['', '/usr/lib/python3.4', '/usr/lib/python3.4/plat-x86_64-linux-gnu', '/usr/lib/python3.4/lib-dynload', '/var/www/lib/python3.4/site-packages']

In a fileImport.py (inside my virtual env) :

# fileImport.py
import sys
print(sys.path)

the command :

$(env) python fileImport.py

gives me the same good result!

But when I try to import the fileImport package from anotherfile.py like this :

#!/usr/bin/env python    
# anotherfile.py    
import fileImport

the sys.path result change :

$(env) python anotherfile.py
['/var/www', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages']

I install pyenv like this :

$ sudo apt-get install python3.4-venv python3-dev
$ pyvenv-3.4 env

I don't understand why the import from a file uses the sys.path from my system and not from my virtual env.

Thank you in advance for your help.

I solved the problem by changing the shebang.

In a virtual env you can use :

$(env) /usr/bin/env python

but in a file the shebang must point to the exact location of your virtual python. In my case :

#!/var/www/bin/python

I hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM