Skip to content

Commit

Permalink
Improve interactive mode detection (theskumar#183)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
Saurabh Kumar authored Jun 2, 2019
1 parent 6d6e18f commit 16f0fa6
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 2 deletions.
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,7 @@ Changelog
Unreleased
-----

- Improve interactive mode detection ([@andrewsmith])([#183]).
- Refactor parser to fix parsing inconsistencies ([@bbc2])([#170]).
- Interpret escapes as control characters only in double-quoted strings.
- Interpret `#` as start of comment only if preceded by whitespace.
Expand Down Expand Up @@ -430,7 +431,9 @@ Unreleased
[#121]: https://github.com/theskumar/python-dotenv/issues/121
[#176]: https://github.com/theskumar/python-dotenv/issues/176
[#170]: https://github.com/theskumar/python-dotenv/issues/170
[#183]: https://github.com/theskumar/python-dotenv/issues/183

[@andrewsmith]: https://github.com/andrewsmith
[@asyncee]: https://github.com/asyncee
[@greyli]: https://github.com/greyli
[@venthur]: https://github.com/venthur
Expand Down
10 changes: 8 additions & 2 deletions src/dotenv/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,14 @@ def find_dotenv(filename='.env', raise_error_if_not_found=False, usecwd=False):
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

def _is_interactive():
""" Decide whether this is running in a REPL or IPython notebook """
main = __import__('__main__', None, None, fromlist=['__file__'])
return not hasattr(main, '__file__')

if usecwd or _is_interactive():
# Should work without __file__, e.g. in REPL or IPython notebook.
path = os.getcwd()
else:
# will work for .py files
Expand Down

0 comments on commit 16f0fa6

Please sign in to comment.