python脚本环境_在一个python脚本中加载环境模块

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

解决方案

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']

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值