[問題] 請問為何os.getcwd()不總在sys.path內?

看板Python作者 (missing)時間6年前 (2018/06/18 00:40), 6年前編輯推噓1(1010)
留言11則, 3人參與, 6年前最新討論串1/4 (看更多)
假設我有一個資料夾(helloworld)在桌面上,結構如下: helloworld |--say_hello.py |--another_hello |--import_hello.py say_hello.py: ```python def hello_world(): print("Hello World!") if __name__ == "__main__": hello_world() ``` import_hello.py: ```python import os print(os.getcwd()) print(os.listdir()) # import sys # sys.path.append(".") import say_hello say_hello.hello_world() ``` 這時候,如果我在helloworld資料夾裡執行`python another_hello/import_hello.py`, 會得到: /Users/clsmbstu/Desktop/helloworld ['__pycache__', 'another_hello', 'say_hello.py'] Traceback (most recent call last): File "another_hello/import_hello.py", line 5, in <module> import say_hello ModuleNotFoundError: No module named 'say_hello' 一旦我把import_hello.py裡面那兩行un-comment, 我就可以得到我的預期結果("Hello World!"), 但我仍然有兩個問題覺得很困惑: 1. 明明cwd (current working directory)是helloworld/, os.listdir()也有找到say_hello.py, 為什麼會有ModuleNotFoundError, 反而還要把cwd加進sys.path裡? 這有點違反我的直覺... 還是cwd是呼叫的位置、sys.path是被呼叫的py檔的位置? 2. 即使用了sys.path.append("."),我仍然擔心這不是個好解法, 因為一旦我從別的資料夾呼叫import_hello.py, 一樣會發生ModuleNotFoundError。 有沒有什麼辦法,是可以無論我在哪裡呼叫import_hello.py, Python都知道要「去import_hello.py的上一層目錄尋找say_hello模組」? 謝謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.121.6.93 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1529253606.A.05E.html ※ 編輯: clsmbstu (122.121.6.93), 06/18/2018 00:45:35

06/18 00:53, 6年前 , 1F

06/18 10:28, 6年前 , 2F
謝謝,但這似乎只適用於package內?
06/18 10:28, 2F

06/18 10:30, 6年前 , 3F
我的案例並沒有__init__.py
06/18 10:30, 3F

06/18 10:33, 6年前 , 4F
而且即使我把所有資料夾都加了一個__init__.py
06/18 10:33, 4F

06/18 10:34, 6年前 , 5F
然後在import_hello裡面寫 from .. import say_hello
06/18 10:34, 5F

06/18 10:34, 6年前 , 6F
ValueError: attempted relative import beyond
06/18 10:34, 6F

06/18 10:35, 6年前 , 7F
top-level package
06/18 10:35, 7F

06/18 10:35, 6年前 , 8F
會有這樣的錯誤回傳
06/18 10:35, 8F

06/18 19:46, 6年前 , 9F
我蠻好奇,有什麼理由要把script和package放在一起嗎
06/18 19:46, 9F

06/18 19:46, 6年前 , 10F
就連手動加進sys.path也是不好的手段
06/18 19:46, 10F

06/21 17:59, 6年前 , 11F
那個script是package自我檢測的工具 @@
06/21 17:59, 11F
文章代碼(AID): #1R9exc1U (Python)
文章代碼(AID): #1R9exc1U (Python)