2016-03-14 102 views
0

我希望我的代碼分割成多個文件在Python 3分割我的代碼分割成多個文件在Python 3

我有以下文件:

/hello 
    __init__.py 
    first.py 
    second.py 

當上述文件的內容:

first.py

from hello.second import say_hello 

say_hello() 

second.py

def say_hello(): 
    print("Hello World!") 

但是當我運行:

python3 first.py 

而在hello目錄我得到以下錯誤:

Traceback (most recent call last): 
    File "first.py", line 1, in <module> 
    from hello.second import say_hello 
ImportError: No module named 'hello' 
+2

你真的*安裝了*你的包嗎?將它添加到路徑中?考慮一個相對導入('from .second import say_hello')而不是? – jonrsharpe

+0

我沒想到你需要。我只是想將我的代碼拆分爲多個文件,就像幾乎所有語言(如Java或PHP)一樣。 –

+1

然後我建議你停止猜測並閱讀例如https://docs.python.org/3/tutorial/modules.html – jonrsharpe

回答

0

換出

from hello.second import say_hello 

from second import say_hello 

你默認的Python路徑將包括當前目錄,所以從second進口直會工作。您甚至不需要此文件__init__.py。您,但是,需要__init__.py文件,如果你想從包裝的外面導入:

$ python3 
>>> from hello.second import say_hello 
>>> # Works ok! 
+2

'__init __。py'在Python 3中不再需要。參見[PEP 420](https://www.python.org/dev/peps/pep-0420 /) – Bharel

+0

當你在package目錄之外時,你的建議會導致'import hello.first'問題。 –

0

你不應該運行在hello目錄python3。

你應該hello目錄外運行並運行

python3 
>>> import hello.first 

順便說一句,不再需要在Python 3見PEP 420__init__.py

+0

這給我的錯誤:'回溯(最近通話最後一個): 文件 「你好/ first.py」,1號線,在 從hello.second進口say_hello 導入錯誤:沒有名爲「模塊hello'' –

+0

@ YahyaUddin:這個答案有效,你一定做錯了。 –

0

包並不意味着從當前目錄導入。

可以使用if/else測試或try/except處理程序使其工作,但它的工作量比它值得的更多。

只是cd ..所以你不在包的目錄中,它會正常工作。