2017-02-23 78 views
1

我的Python版本是3.5。Python和從另一個包導入

我有這樣與結構的項目:

內容的
-- test 
---- __init__.py 
---- one 
------ __init__.py 
------ first.py 
---- two 
------ __init__.py 
------ second.py 

first.py文件:

內容的
class FirstClass(object): 

    def hello(self): 
     return 'hello' 

second.py文件:

def main(): 
    first = FirstClass() 
    print(first.hello()) 

if __name__ == '__main__': 
    main() 

的問題是,我可以在中不輸入,我想:

from test.one.first import FirstClass 

Result: 

Traceback (most recent call last): 
    File "second.py", line 3, in <module> 
    from test.one.first import FirstClass 
ModuleNotFoundError: No module named 'test.one' 

另外,我試過這種方法:

from ..one.first import FirstClass 

Result: 

Traceback (most recent call last): 
    File "second.py", line 3, in <module> 
    from ..one.first import FirstClass 
ValueError: attempted relative import beyond top-level package 

所以,我的問題是:如何做在這樣的情況下導入?

+0

見:http://stackoverflow.com/questions/8706309/how-to-reference-to -python-top-level-modules-in-package – putonspectacles

+0

另一個相關問題:http://stackoverflow.com/questions/16981921/relative-imports-in-python-3 – Leon

回答

0

這是一個黑客但卻將工作:

def main(): 
    first = FirstClass() 
    print(first.hello()) 

if __name__ == '__main__': 
    from sys import path 
    from os.path import dirname as dir 

    path.append(dir(path[0])) 
    __package__ = "one" 
    from one.first import FirstClass 
    main() 

看到:萊昂在評論鏈接