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.py
在lib
。
如果我更改了hello.py
到import 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」的信息可能是有用的,但我不明白如何使他們在實踐中我的問題。
似乎在Python 2中爲我工作。 –
請問我的[類似問題](http://stackoverflow.com/questions/39528736/how-do-you-organise-a-python-project-that-contains-multiple-packages那麼這個eac)的幫助? – Pod