在导入语句之前设置pythonpath [英] set pythonpath before import statements

查看:83
本文介绍了在导入语句之前设置pythonpath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是:

import scriptlib.abc
import scriptlib.xyz

def foo():
  ... some operations

但是scriptlib在其他目录中,因此我必须将该目录包含在环境变量"PYTHONPATH"中.

but the scriptlib is in some other directory, so I will have to include that directory in environment variable "PYTHONPATH".

无论如何,在导入语句执行之前,我可以首先在环境变量"PYTHONPATH"中添加scriptlib目录:

Is there anyway in which I can first add the scriptlib directory in environment variable "PYTHONPATH" before import statement getting executed like :

import sys
sys.path.append('/mypath/scriptlib')
import scriptlib.abc
import scriptlib.xyz

def foo():
  ... some operations

如果是,则仅是该命令提示符的值还是全局值?

If so, is the value only for that command prompt or is it global ?

预先感谢

推荐答案

这将为您的Python进程/实例(即正在运行的可执行文件)添加路径.该路径不会为任何其他Python进程修改.另一个正在运行的Python程序将不会修改其路径,并且如果您退出程序并再次运行,则该路径将不包含您之前添加的内容.您在做什么通常是正确的.

This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.

set.py:

import sys
sys.path.append("/tmp/TEST")

loop.py

import sys
import time
while True:
  print sys.path
  time.sleep(1)

运行:python loop.py &

这将运行loop.py,并连接到您的STDOUT,并将继续在后台运行.然后可以运行python set.py.每个都有一组不同的环境变量.观察到loop.py的输出不会更改,因为set.py不会更改loop.py的环境.

This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py. Each has a different set of environment variables. Observe that the output from loop.py does not change because set.py does not change loop.py's environment.

有关导入的提示

Python导入与其他语言一样是动态的.没有进行静态链接.导入是可执行行,就像sys.path.append....

Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append....

这篇关于在导入语句之前设置pythonpath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆