Skip to content

Commit ad75a0a

Browse files
author
Saurabh Kumar
committed
Improve interactive mode detection
Previously, this checked whether __file__ was defined in globals(). globals() is tied to the current module, so this will always be defined. Fix this by importing __main__ and asking whether it has __file__ defined. This approach is outlined in stackoverflow.com/a/2356420. Thanks @andrewsmith
1 parent 436b1be commit ad75a0a

1 file changed

Lines changed: 8 additions & 2 deletions

File tree

‎src/dotenv/main.py‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -235,8 +235,14 @@ def find_dotenv(filename='.env', raise_error_if_not_found=False, usecwd=False):
235235
236236
Returns path to the file if found, or an empty string otherwise
237237
"""
238-
if usecwd or '__file__' not in globals():
239-
# should work without __file__, e.g. in REPL or IPython notebook
238+
239+
def _is_interactive():
240+
""" Decide whether this is running in a REPL or IPython notebook """
241+
main = __import__('__main__', None, None, fromlist=['__file__'])
242+
return not hasattr(main, '__file__')
243+
244+
if usecwd or _is_interactive():
245+
# Should work without __file__, e.g. in REPL or IPython notebook.
240246
path = os.getcwd()
241247
else:
242248
# will work for .py files

0 commit comments

Comments
 (0)