天天看點

python程式設計求極限_對相關python進口的極限答案

看看

PEP 328的以下資訊:

Relative imports use a module’s __name__ attribute to determine that module’s position in the package hierarchy. If the module’s name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module,regardless of where the module is actually located on the file system.

當您将foo.py作為腳本運作時,該子產品的__name__是“__main__”,是以您不能進行相對導入.即使mypackage在sys.path上也是如此.基本上,如果導入了該子產品,則隻能從子產品進行相對導入.

以下是解決這個問題的幾個選擇:

1)在foo.py中,檢查是否__name__ ==’__main__’,并有條件地将mypackage添加到sys.path中:

if __name__ == '__main__':

import os,sys

# get an absolute path to the directory that contains mypackage

foo_dir = os.path.dirname(os.path.join(os.getcwd(),__file__))

sys.path.append(os.path.normpath(os.path.join(foo_dir,'..','..')))

from mypackage import bar

else:

from .. import bar

2)始終使用mypackage導入欄導入欄,并執行foo.py,使得mypackage可以自動顯示:

$cd

$python -m mypackage.foo.foo