作者cutekid (可爱小孩子)
看板Python
标题Re: [问题] 请问为何os.getcwd()不总在sys.path内?
时间Mon Jun 18 14:17:36 2018
import os,sys,inspect
#####################################
# get file dir then add relative path
file = inspect.getfile(inspect.currentframe())
pathdir = os.path.dirname(os.path.abspath(
file)) +
'/..'
sys.path.insert(
0,pathdir)
####################
# import your module
import say_hello
say_hello.hello_world()
※ 引述《clsmbstu (missing)》之铭言:
: 假设我有一个资料夹(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), 来自: 61.223.33.167
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1529302658.A.E14.html
1F:推 justoncetime: 推标色 06/18 15:58
2F:→ clsmbstu: 感谢 我再研究一下 06/21 18:00