-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix bug: top-level script checking should only ignore the frames with…
…in `importlib`
- Loading branch information
Showing
1 changed file
with
39 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,49 @@ | ||
import os | ||
import sys | ||
|
||
f = sys._getframe(1) | ||
while f.f_code is not None and f.f_code.co_filename.startswith('<'): | ||
f = f.f_back | ||
|
||
if f and f.f_code and f.f_code.co_filename.startswith(os.path.dirname(os.__file__)): | ||
def _is_run_as_script(): | ||
""" | ||
Check that whether lambdex is run as top-level script. | ||
We iterate from the stack bottom to find the first frame that contains | ||
no 'importlib' string, which should be the importer of lambdex. | ||
If the importer has any system prefixes, we assert that lambdex is run | ||
as top-level script. | ||
""" | ||
import site | ||
from os.path import dirname, abspath | ||
|
||
f = sys._getframe(1) | ||
while f is not None \ | ||
and f.f_code is not None \ | ||
and 'importlib' in f.f_code.co_filename: | ||
f = f.f_back | ||
|
||
if not (f or f.f_code): | ||
return False | ||
|
||
filename = abspath(f.f_code.co_filename) | ||
for sitepath in site.getsitepackages() + [site.getusersitepackages()]: | ||
prefix = dirname(dirname(dirname(sitepath))) # such as '/usr/local' | ||
if filename.startswith(prefix): | ||
return True | ||
|
||
return False | ||
|
||
|
||
# If run as top-level script, user is happened to use lxfmt. | ||
# We remove CWD from sys.path, so that the files user editting will not | ||
# cause name conflicts with built-in modules. | ||
if _is_run_as_script(): | ||
if sys.path and sys.path[0] == os.getcwd(): | ||
sys.path = sys.path[1:] | ||
# Otherwise, we import keywords as normal | ||
else: | ||
__all__ = ['def_'] | ||
from .keywords import def_ | ||
from .keywords import * | ||
from .keywords import __all__ | ||
|
||
del os, sys, f | ||
del os, sys, _is_run_as_script | ||
|
||
__version__ = "0.2.0" |