qpython手机版文件路径_如何使用完整的路径导入python包或qinit_uuy.py文件?

在QPython手机版中,遇到导入位于特定路径的Python包时遇到问题。文章通过创建临时模块来演示如何在系统路径未包含模块的情况下,尝试使用完整路径导入。尽管尝试了插入目录到系统路径、使用`__import__`函数,但仍然无法避免导入冲突和相对导入错误。示例代码展示了如何导入具有相同名称但不同值的模块。
摘要由CSDN通过智能技术生成

我有一个包:pyfoo在目录/home/user/somedir中

这个包裹是普通的

'/home/user/somedir/pyfoo/\uu init\uy.py'

我希望能够使用其完整路径“/home/user/somedir/pyfoo/”导入此模块

但是当模块是一个包的时候,我似乎不能让它工作。在

我发现的一个非常奇怪的用例是,在用h5py写入一个文件之前,我被深深地嵌入到脚本执行中。在

我不得不卸载h5py并用openmpi重新安装一个并行版本,但是即使卸载了它,h5py(串行)仍然在内存中。我不想重新启动,因为脚本花了很长时间。我试图重新加载模块,但没用。我还试图从文件名导入它,方法是使用目录并使用\uu init_uu.py,但是我得到了相对的导入错误。我甚至尝试将新的安装位置添加到系统路径执行正常的导入,但也失败了。在

我已经在我的个人实用程序库中有一个import_from_filepath函数,我还想添加import_from_dirpath,但我在弄清楚它是如何实现的方面有点麻烦。在

下面是一个脚本来说明这个问题:# Define two temporary modules that are not in sys.path

# and have the same name but different values.

import sys, os, os.path

def ensuredir(path):

if not os.path.exists(path):

os.mkdir(path)

ensuredir('tmp')

ensuredir('tmp/tmp1')

ensuredir('tmp/tmp2')

ensuredir('tmp/tmp1/testmod')

ensuredir('tmp/tmp2/testmod')

with open('tmp/tmp1/testmod/__init__.py', 'w') as file_:

file_.write('foo = \"spam\"\nfrom . import sibling')

with open('tmp/tmp1/testmod/sibling.py', 'w') as file_:

file_.write('bar = \"ham\"')

with open('tmp/tmp2/testmod/__init__.py', 'w') as file_:

file_.write('foo = \"eggs\"\nfrom . import sibling')

with open('tmp/tmp1/testmod/sibling.py', 'w') as file_:

file_.write('bar = \"jam\"')

# Neither module should be importable through the normal mechanism

try:

import testmod

assert False, 'should fail'

except ImportError as ex:

pass

# Try temporarilly adding the directory of a module to the path

sys.path.insert(0, 'tmp/tmp1')

testmod1 = __import__('testmod', globals(), locals(), 0)

sys.path.remove('tmp/tmp1')

print(testmod1.foo)

print(testmod1.sibling.bar)

sys.path.insert(0, 'tmp/tmp2')

testmod2 = __import__('testmod', globals(), locals(), 0)

sys.path.remove('tmp/tmp2')

print(testmod2.foo)

print(testmod2.sibling.bar)

assert testmod1.foo == "spam"

assert testmod1.sibling.bar == "ham"

# Fails, returns spam

assert testmod2.foo == "eggs"

assert testmod2.sibling.bar == "jam"

在系统路径无法通过路径导入。它默认导入先前加载的模块。在

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值