python-dotenvモジュールをpipインストールしました。次のように使用しようとしています。私は、次のツリーでディレクトリtest_dotenv
を作成しました:python-dotenvの "find_dotenv"メソッドの使用方法
.
├── config.env
└── test_dotenv_subdir
└── test_dotenv.py
test_dotenv.py
には、以下が含まれていながらconfig.env
ファイルは、単純に空のファイルです:
import dotenv
found_dotenv = dotenv.find_dotenv()
print(found_dotenv)
しかし、私はpython test_dotenv.py
を使用してこのスクリプトを実行する場合私は何も印刷されていないことがわかります。つまり、found_dotenv
は空の文字列(''
)です。
私はこの方法の使い方について何か不足していますか?私の知る限り、ここでsource codeの関連部分は次のとおりです。最後に空の文字列が返されるようにos.path.exists(check_path)
は、False
を返すに保つよう
def _walk_to_root(path):
"""
Yield directories starting from the given directory up to the root
"""
if not os.path.exists(path):
raise IOError('Starting path not found')
if os.path.isfile(path):
path = os.path.dirname(path)
last_dir = None
current_dir = os.path.abspath(path)
while last_dir != current_dir:
yield current_dir
parent_dir = os.path.abspath(os.path.join(current_dir, os.path.pardir))
last_dir, current_dir = current_dir, parent_dir
def find_dotenv(filename='.env', raise_error_if_not_found=False, usecwd=False):
"""
Search in increasingly higher folders for the given file
Returns path to the file if found, or an empty string otherwise
"""
if usecwd or '__file__' not in globals():
# should work without __file__, e.g. in REPL or IPython notebook
path = os.getcwd()
else:
# will work for .py files
frame_filename = sys._getframe().f_back.f_code.co_filename
path = os.path.dirname(os.path.abspath(frame_filename))
for dirname in _walk_to_root(path):
check_path = os.path.join(dirname, filename)
if os.path.exists(check_path):
return check_path
if raise_error_if_not_found:
raise IOError('File not found')
return ''
に思えます。なぜこれは意図したとおりに動作していないのですか?