在Python软件包中导入文件
我将如何在Python软件包中导入另一个文件。我使用包裹安装,
pip install .
以便我可以使用
python3 -m pkg
以下是文件结构来运行它:
。
├前pkg
│⠀⠀├─Cli.py
│⠀⠀├ - __init__.py
│⠀⠀├ - __ -main__.py
├├前Readme.md
我尝试通过使用__ -main__.py
中的cli.py导入函数,
import .cli as clifunc
但会导致错误导致错误
root@localhost:~# python3 -m pkg
import .cli as clifunc
^
SyntaxError: invalid syntax
?我如何导入文件?我尝试过的其他方法导致错误是该文件不是模块!?!我该如何导入文件?
How would I go about importing another file in a python package. I install the package with
pip install .
so I can then run it using
python3 -m pkg
Here's the file structure:
.
├── pkg
│⠀⠀├── cli.py
│⠀⠀├── __init__.py
│⠀⠀├── __main__.py
├── README.md
└── setup.py
I try to import a function from cli.py in __main__.py by using
import .cli as clifunc
but it results in an error
root@localhost:~# python3 -m pkg
import .cli as clifunc
^
SyntaxError: invalid syntax
How do I import the file? Other methods I've tried resulted in the error being that the file isn't a module!?! How can I just import the file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因此,显然,当使用显式相对导入时(使用
.cli
)时,您不能仅使用import .module
(不确定为什么,也许其他人也可以这样做)您需要从中使用
。导入模块
so
来自。导入CLI作为Clifunc
应该起作用。So apparently when using the explicit relative imports (using dots like
.cli
), you can't just useimport .module
(not sure quite why though, maybe someone else does)You instead need to use
from . import module
So
from . import cli as clifunc
should work.