[英]How to use python-dotenv's “find_dotenv” method
I've pip-installed the python-dotenv module and am trying to use it as follows. 我已经点子安装了python-dotenv模块,并尝试如下使用它。 I've created a directory
test_dotenv
with the following tree: 我用以下树创建了一个目录
test_dotenv
:
.
├── config.env
└── test_dotenv_subdir
└── test_dotenv.py
The config.env
file is simply an empty file, while test_dotenv.py
contains the following: config.env
文件只是一个空文件,而test_dotenv.py
包含以下内容:
import dotenv
found_dotenv = dotenv.find_dotenv()
print(found_dotenv)
However, if I run this script using python test_dotenv.py
, I find that nothing gets printed; 但是,如果我使用
python test_dotenv.py
运行此脚本,我发现什么都不会打印; that is, found_dotenv
is an empty string ( ''
). 也就是说,
found_dotenv
是空字符串( ''
)。
Am I missing something about how to use this method? 我是否缺少有关如何使用此方法的信息? As far as I can tell, here is the relevant part of the source code :
据我所知,这是源代码的相关部分:
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 ''
It seems like os.path.exists(check_path)
keeps on returning False
, so that the in the end an empty string is returned. 似乎
os.path.exists(check_path)
继续返回False
,因此最终返回了一个空字符串。 Why is this not working as intended? 为什么这不能按预期工作?
The dotenv
package looks for a file that is literally called .env
when you call find_dotenv
rather than looking for files like .env
. 该
dotenv
包查找一个被称为字面上文件.env
当你调用find_dotenv
而不是找像文件.env
。
You can make your code find the desired file by passing the filename to find_dotenv
, ie 您可以通过将文件名传递给
find_dotenv
来使代码找到所需的文件,即
import dotenv
found_dotenv = dotenv.find_dotenv('config.dotenv')
print(found_dotenv)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.