python导入包路径_Python路径说明:从子包导入

This questions is detailing a behavior that I can't explain to myself.

src/package/__init__.py is empty but present.

src/package/subpackage/__init__.py:

pink = 'It works'

src/package/test/test.py:

import package.subpackage as subpackage

# I also tried `import package.subpackage as subpackage

print subpackage.pink

Calling from src: python package/test/test.py just fails with ImportError: No module named subpackage. Please note that import package doesn't work either.

NB: (Running an interpreter from src and typing the import statement works perfectly well.

Should I understand that I'm not suppose to call subfile of a package? In my project it's a test file so it sounds logical for me have it here.

Why the current working directory is not in the import path?

Many thanks for those who reads and those who answers.

解决方案

Because you package is not in $PYTHONPATH. If you what to call test.py, you can move your test.py file to src/ directory, or add src to $PYTHONPATH

PYTHONPATH="/path/to/src:$PYTHONPATH"

export PYTHONPATH

From Documentation

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path

>>> import sys

>>> sys.path

The output is like this

['.', '/usr/bin', ...

This means that the current directory is in sys.path as well. If you want to import a module, please make sure that the module path is in sys.path, by adding your package directory to the environment variable PYTHONPATH, or changing your current directory or script directory to the package directory.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值