diff --git a/NEWS.rst b/NEWS.rst index 1be077e..eb0aaf8 100644 --- a/NEWS.rst +++ b/NEWS.rst @@ -22,6 +22,7 @@ New Features * Added `mangle` and `unmangle` as core functions * `defclass` in Python 3 now supports specifying metaclasses and other keyword arguments +* Added a command-line option `-E` per CPython Bug Fixes ------------------------------ diff --git a/hy/cmdline.py b/hy/cmdline.py index 151b6eb..779ec40 100644 --- a/hy/cmdline.py +++ b/hy/cmdline.py @@ -271,6 +271,8 @@ def cmdline_handler(scriptname, argv): help="program passed in as a string") parser.add_argument("-m", dest="mod", help="module to run, passed in as a string") + parser.add_argument("-E", action='store_true', + help="ignore PYTHON* environment variables") parser.add_argument("-i", dest="icommand", help="program passed in as a string, then stay in REPL") parser.add_argument("--spy", action="store_true", @@ -310,6 +312,10 @@ def cmdline_handler(scriptname, argv): # reset sys.argv like Python sys.argv = options.args + module_args or [""] + if options.E: + # User did "hy -E ..." + _remove_python_envs() + if options.command: # User did "hy -c ..." return run_command(options.command) @@ -436,3 +442,10 @@ def _print_for_windows(src): print(line) except: print(line.encode('utf-8')) + +# remove PYTHON* environment variables, +# such as "PYTHONPATH" +def _remove_python_envs(): + for key in list(os.environ.keys()): + if key.startswith("PYTHON"): + os.environ.pop(key) diff --git a/tests/resources/bin/printenv.hy b/tests/resources/bin/printenv.hy new file mode 100644 index 0000000..521fd27 --- /dev/null +++ b/tests/resources/bin/printenv.hy @@ -0,0 +1,3 @@ +(import os) + +(print (. os environ)) diff --git a/tests/test_bin.py b/tests/test_bin.py index b1e0b25..ad74781 100644 --- a/tests/test_bin.py +++ b/tests/test_bin.py @@ -168,6 +168,23 @@ def test_bin_hy_stdin_hy_repr(): output, _ = run_cmd(hr("--spy"), '(+ [1] [2] (foof))') assert "[1]+[2]" in output.replace('L', '').replace(' ', '') +def test_bin_hy_ignore_python_env(): + os.environ.update({"PYTHONTEST": '0'}) + output, _ = run_cmd("hy -c '(print (do (import os) (. os environ)))'") + assert "PYTHONTEST" in output + output, _ = run_cmd("hy -m tests.resources.bin.printenv") + assert "PYTHONTEST" in output + output, _ = run_cmd("hy tests/resources/bin/printenv.hy") + assert "PYTHONTEST" in output + + output, _ = run_cmd("hy -E -c '(print (do (import os) (. os environ)))'") + assert "PYTHONTEST" not in output + os.environ.update({"PYTHONTEST": '0'}) + output, _ = run_cmd("hy -E -m tests.resources.bin.printenv") + assert "PYTHONTEST" not in output + os.environ.update({"PYTHONTEST": '0'}) + output, _ = run_cmd("hy -E tests/resources/bin/printenv.hy") + assert "PYTHONTEST" not in output def test_bin_hy_cmd(): output, _ = run_cmd("hy -c \"(koan)\"")