2016-10-21 35 views
1

我有一個腳本hello.py它可以用作main.py的模塊,或者從命令行調用。它本身導入一個模塊helper.py這是在同一個目錄下:如何組織模塊的子文件夾,也稱爲腳本?

├── lib 
│   ├── hello.py 
│   ├── helper.py 
│   ├── __init__.py 
├── main.py 

文件的內容是

$ cat main.py 
import lib.hello 

lib.hello.sayhi() 

------------------------------------ 

$ cat lib/hello.py 
import helper 

def sayhi(): 
    print("bonjour") 
    print(helper.something()) 

if __name__ == "__main__": 
    print("hello") 

------------------------------------ 

$ cat lib/helper.py 
def something(): 
    print("something") 

我的問題是,你好從從命令行調用工作正常(進口helper.py正確的,因爲它是在同一水平E爲hello.py),但運行main.py當我得到

$ python3 main.py 
Traceback (most recent call last): 
    File "main.py", line 1, in <module> 
    import lib.hello 
    File "/tmp/lib/hello.py", line 1, in <module> 
    import helper 
ImportError: No module named 'helper' 

,因爲從日e透視main.py,helper.pylib

如果我更改了hello.pyimport lib.helper後來我有同樣的問題反過來進口:

$ python3 hello.py 
Traceback (most recent call last): 
    File "hello.py", line 1, in <module> 
    import lib.helper 
ImportError: No module named 'lib' 

如何擺脫這種趕上22日的情況呢?

我猜想,從「PEP 338 -- Executing modules as scripts」的信息可能是有用的,但我不明白如何使他們在實踐中我的問題。

+0

似乎在Python 2中爲我工作。 –

+0

請問我的[類似問題](http://stackoverflow.com/questions/39528736/how-do-you-organise-a-python-project-that-c​​ontains-multiple-packages那麼這個eac)的幫助? – Pod

回答

0

你應該hello.py

import lib.helper 

並在呼叫建立做一些方法:

lib.helper.something() 

這解決您的問題,您可以撥打主或打招呼沒有問題