python 本地模块
我有几个项目目录,并且想要特定于它们的库/模块。例如,我可能有这样的目录结构:
myproject/
mymodules/
__init__.py
myfunctions.py
myreports/
mycode.py
假设 myfunctions.py
中有一个名为 add
的函数,我可以从 mycode.py< /code> 使用最幼稚的例程:
execfile('../mymodules/myfunctions.py')
add(1,2)
但要更复杂一点,我也可以这样做
import sys
sys.path.append('../mymodules')
import myfunctions
myfunctions.add(1,2)
这是最惯用的方法吗?还有一些提到修改 PYTHONPATH
(os.environ['PYTHONPATH']
?),但是这是我应该研究的还是其他事情?
另外,我还看到类语句中包含 import
语句,在其他实例中,这些语句定义在包含类定义的 Python 文件的顶部。有没有正确/首选的方法来做到这一点?
I have several project directories and want to have libraries/modules that are specific to them. For instance, I might have a directory structure like such:
myproject/
mymodules/
__init__.py
myfunctions.py
myreports/
mycode.py
Assuming there is a function called add
in myfunctions.py
, I can call it from mycode.py
with the most naive routine:
execfile('../mymodules/myfunctions.py')
add(1,2)
But to be more sophisticated about it, I can also do
import sys
sys.path.append('../mymodules')
import myfunctions
myfunctions.add(1,2)
Is this the most idiomatic way to do this? There is also some mention about modifying the PYTHONPATH
(os.environ['PYTHONPATH']
?), but is this or other things I should look into?
Also, I have seen import
statements contained within class statements, and in other instances, defined at the top of a Python file which contains the class definition. Is there a right/preferred way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要乱用
execfile
或sys.path.append
除非有很好的理由。相反,只需将您的代码安排到 适当的 python 包 中,然后像导入任何其他库一样进行导入。如果您的
mymodules
实际上是一个大型项目的一部分,则像这样设置您的包:然后您可以从代码中的任何位置导入
mymodules
,如下所示:您的
mymodules
代码由许多独立且不同的项目使用,然后将其单独放入一个包中,并将其安装到需要使用的任何环境中。Don't mess around with
execfile
orsys.path.append
unless there is some very good reason for it. Rather, just arrange your code into proper python packages and do your importing as you would any other library.If your
mymodules
is in fact a part of one large project, then set your package up like so:And then you can import
mymodules
from anywhere in your code like this:If your
mymodules
code is used by a number of separate and distinct projects, then just make it into a package in its own right and install it into whatever environment it needs to be used in.