python编程求极限_对相关python进口的极限答案

当Python模块作为脚本运行时,如果__name__为'__main__',相对导入会失效。解决方法是在foo.py中检查__name__,根据情况动态添加mypackage到sys.path。一种方案是条件性地添加路径,另一种是通过执行命令行来确保mypackage可见。这涉及到Python的包管理和模块导入机制。
摘要由CSDN通过智能技术生成

看看

PEP 328的以下信息:

Relative imports use a module’s __name__ attribute to determine that module’s position in the package hierarchy. If the module’s name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module,regardless of where the module is actually located on the file system.

当您将foo.py作为脚本运行时,该模块的__name__是“__main__”,因此您不能进行相对导入.即使mypackage在sys.path上也是如此.基本上,如果导入了该模块,则只能从模块进行相对导入.

以下是解决这个问题的几个选择:

1)在foo.py中,检查是否__name__ ==’__main__’,并有条件地将mypackage添加到sys.path中:

if __name__ == '__main__':

import os,sys

# get an absolute path to the directory that contains mypackage

foo_dir = os.path.dirname(os.path.join(os.getcwd(),__file__))

sys.path.append(os.path.normpath(os.path.join(foo_dir,'..','..')))

from mypackage import bar

else:

from .. import bar

2)始终使用mypackage导入栏导入栏,并执行foo.py,使得mypackage可以自动显示:

$cd

$python -m mypackage.foo.foo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值