简体   繁体   English

python导入相关模块

[英]python importing relative modules

I have the Python modules a.py and b.py in the same directory. 我在同一目录中有Python模块a.py和b.py。 How can I reliably import b.py from a.py, given that a.py may have been imported from another directory or executed directly? 考虑到a.py可能是从另一个目录导入或直接执行的,我如何可靠地从a.py导入b.py? This module will be distributed so I can't hardcode a single path. 该模块将是分布式的,因此我无法对单个路径进行硬编码。

I've been playing around with __file__ , sys.path and os.chdir, but it feels messy. 我一直在玩弄__file__ ,sys.path中和os.chdir,但感觉凌乱。 And __file__ is not always available. __file__并非始终可用。

Actually, __file__ is available for an imported module, but only if it was imported from a .py/.pyc file. 实际上, __file__可用于导入的模块,但仅当它是从.py / .pyc文件导入时才可用。 It won't be available if the module is built in. For example: 如果模块是内置的,它将不可用。例如:

>>> import sys, os
>>> hasattr(os, '__file__')
True
>>> hasattr(sys, '__file__')
False

Using the inspect module will make the builtin modules more obvious: 使用inspect模块将使内置模块更加明显:

>>> import os
>>> import sys
>>> inspect.getfile(os)
'/usr/local/lib/python2.6/os.pyc'
>>> inspect.getfile(sys)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/inspect.py", line 407, in getfile
    raise TypeError('arg is a built-in module')
TypeError: arg is a built-in module

将包含两者的目录放入您的python路径中,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM