我在使用virtualenv的python中使用redis库。
我有一个文件redis.py
,其中包含以下内容;
import redis
class RedisExtension(Extension):
def __init__(self, config):
print redis
class Redis(Facade):
pass
但是,即使激活了venv文件夹,它似乎也会执行自我导入。 我需要从venv文件夹中创建redis.py import redis,该文件夹由pip 安装redis库,而不更改此处的任何名称。
有没有办法做到这一点?
答案 0 :(得分:3)
默认情况下,Python设置从多个不同路径导入,其中一个是当前路径。
>>> import os
>>> os.sys.path
['',
'/home/javl/Envs/so/bin',
'/home/javl/Envs/so/lib/python2.7',
'/home/javl/Envs/so/lib/python2.7/plat-x86_64-linux-gnu',
'/home/javl/Envs/so/lib/python2.7/lib-tk',
'/home/javl/Envs/so/lib/python2.7/lib-old',
'/home/javl/Envs/so/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/javl/Envs/so/local/lib/python2.7/site-packages',
'/home/javl/Envs/so/lib/python2.7/site-packages',
'/home/javl/Envs/so/local/lib/python2.7/site-packages/IPython/extensions',
'/home/javl/.ipython']
如您所见,第一项是“”。这意味着“这个目录”。删除它:
>>> os.sys.path.remove("")
>>> os.sys.path
['/home/javl/Envs/so/bin',
'/home/javl/Envs/so/lib/python2.7',
'/home/javl/Envs/so/lib/python2.7/plat-x86_64-linux-gnu',
'/home/javl/Envs/so/lib/python2.7/lib-tk',
'/home/javl/Envs/so/lib/python2.7/lib-old',
'/home/javl/Envs/so/lib/python2.7/lib-dynload',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk',
'/home/javl/Envs/so/local/lib/python2.7/site-packages',
'/home/javl/Envs/so/lib/python2.7/site-packages',
'/home/javl/Envs/so/local/lib/python2.7/site-packages/IPython/extensions',
'/home/javl/.ipython']
>>> import redis
如果我们想把东西放回原来的顺序,我们可以通过:
来做>>> os.sys.path.insert(0, "")
您应将此修改内容放入redis.py
os.sys.path.remove("")
import redis
os.sys.path.insert(0, "")
class RedisExtension(Extension):
def __init__(self, config):
print redis
class Redis(Facade):
pass