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

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

问题描述

我的代码是:

import scriptlib.abc
import scriptlib.xyz

def foo():
  ... some operations

但脚本库位于其他目录中,因此我必须将该目录包含在环境变量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天全站免登陆