Skip to content

Commit a1c6eb5

Browse files
author
Saurabh Kumar
authored
Improve interactive mode detection (theskumar#183)
* 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 a1c6eb5

2 files changed

Lines changed: 11 additions & 2 deletions

File tree

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,6 +299,7 @@ Changelog
299299
Unreleased
300300
-----
301301

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

436+
[@andrewsmith]: https://github.com/andrewsmith
434437
[@asyncee]: https://github.com/asyncee
435438
[@greyli]: https://github.com/greyli
436439
[@venthur]: https://github.com/venthur

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)