2016-12-13 2 views
0

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 '' 

に思えます。なぜこれは意図したとおりに動作していないのですか?

答えて

1

dotenvパッケージには、あなたが.envのようなファイルを探しているのではなくfind_dotenvを呼び出すときに、文字通り.envと呼ばれるファイルを探します。

あなたはすなわち

import dotenv 

found_dotenv = dotenv.find_dotenv('config.dotenv') 
print(found_dotenv) 
、あなたのコードがfind_dotenvにファイル名を渡すことにより、目的のファイルを見つけることができます
関連する問題