loading-environment-modules-within-a-python-script

一世执手 提交于 2019-12-06 13:51:49

问题


Loading environment modules within a python script

The above solution behaves differently in the python interactive shell and within an executable python file & I need some help in understanding how to get it to work in the exe.py setting, where import statements appear not to be seeing the environment variable PYTHONPATH.

In python shell the solution allows loading of an environment module which modifies PYTHONPATH; I can subsequently import a python module from that amended PYTHONPATH. This is great functionality & exactly what I want it to do in an executable python script.

In a python script (headed #!/usr/bin/env python etc), it works OK up to and including amendment of PYTHONPATH

if 'PYTHONPATH' in os.environ: print 'PYPATH:', os.environ['PYTHONPATH']
# nothing prints

execfile('/usr/local/Modules/default/init/python.py')
module('list')
# No Modulefiles Currently Loaded.

module('load', 'my_module')
print 'loaded my_module'
# loaded my_module
module('list')
#   1) /my_module
if 'PYTHONPATH' in os.environ: print 'PYPATH:', os.environ['PYTHONPATH']
# /home/me/py/my_module

But that's as far as it works in a python.exe

Attempts to import from my_module which work OK in the python shell result in Traceback reports 'ImportError: No Module named module_1

From this I think I can conclude that python is not using or 'seeing' the amended PYTHONPATH when I run this in the python exe (but does see it when in the interactive python shell).

That's kindof where I get stuck! Any ideas? Help much appreciated. I bet there's a really simple solution I've overlooked & I'll be delighted to hear about it.

thanks & have a great day

Mat

Edit: Some more reading around suggests that python itself adds the content of PYTHONPATH to sys.path, but this is happening in neither the interactive python shell nor when I run the python.exe.

If I use sys.path.insert(1,os.environ['PYTHONPATH']) to do this manually in the exe then I get the functionality I want


回答1:


I think that the pythonpath is read during the initialization for adding paths in sys.path, see some examples in sys.path() and PYTHONPATH issues .

So the variable you need to update is actually only sys.path - when python is already initialized it is too late for updating os.environ['PYTHONPATH']



来源:https://stackoverflow.com/questions/24044373/loading-environment-modules-within-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!