基本的Python导入问题 [英] Basic Python imports question

查看:105
本文介绍了基本的Python导入问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的src目录设置如下:

If I have a src directory setup like this:

main.py
pkg1:
    __init__.py
    util.py
pkg2:
    __init__.py
    test.py

您能否告诉我从 main.py pkg1.util 的最佳方法>和 test.py

Can you tell me the best way to import pkg1.util from main.py and from test.py?

谢谢! (如果我需要在根目录中有另一个 __ init __。py 文件,请告诉我?)

Thanks! (If I need to have another __init__.py file in the root directory, let me know?)

推荐答案

由于您提到这是Python 3,因此您无需将以下内容添加到 .py 文件中。我仍然会,因为如果一些卡在Python 2上的可怜的人需要使用你的代码,它有助于向后移植:

Since you mention that this is Python 3, you do not have to add the following to your .py files. I would still though because it helps backwards portability if some poor sod who's stuck on Python 2 needs to use your code:

from __future__ import absolute_import

鉴于您使用的是Python 3,或者您正在使用Python 2并且已包含上面一行,这是你的答案:

Given that you are using Python 3, or that you're using Python 2 and have included the above line, here is your answer:

来自 main.py

import pkg1.util as util

test.py 您将使用以下两种方式之一,具体取决于您是否考虑 pkg1 pkg2 这些东西总是以相同的方式相互关联,或者它们是否总是在顶层半独立地部署。如果是第一个,你会这样做:

from test.py you would use one of two ways depending on whether you considered pkg1 and pkg2 to be things that would always deployed together in the same way in relation to each other, or whether they will instead always be each deployed semi-independently at the top level. If the first, you would do this:

from ..pkg1 import util

如果这是第二个选项,那么:

and if it's the second option, this:

import pkg1.util as util

这当然意味着你总是运行Python main.py 所在的目录,或该目录位于 PYTHONPATH 中或以 sys.path 由于某种原因(例如,作为主要的Python site-packages目录)。

This implies, of course, that you are always running Python from the directory in which main.py is, or that that directory is in PYTHONPATH or ends up in sys.path for some reason (like being the main Python site-packages directory for example).

这篇关于基本的Python导入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆