Search code examples
pythonbatch-fileenvironment-variablessubprocesspython-os

Python script kicked off from batch file can't see env vars set in batch file


I am using a .bat file to:

  1. Set environment variables
  2. Kick off a Python program (that uses these environment variables)
@ECHO OFF
REM TODO: figure out why Python can't see this
SET MY_ENV_VAR="foo"

CALL C:\code\repo\venv\Scripts\activate
CD /d C:\code\repo
@ECHO ON
REM kick off Python, where os.getenv can't see MY_ENV_VAR
CMD /k run_python_console_script

If you're curious, the run_python_console_script kicks off a command made via an Entry Point.

When I run os.getenv("MY_ENV_VAR") it doesn't return "foo", it returns None. Why is this?

I don't want to use SETX (docs), I want the environment variable scoped to just this batch script.


Other Answers

How to access Batch Script variables in python? and Python Subprocess Does not Get Environment Variable from Bat File want to invoke a .bat script as a subprocess. I don't want to do this, the .bat script is my parent process.

virtualenvwrapper supports a postactivate script (see How can I use a postactivate script using Python 3 venv? and Set specific environment variables activating a Python virtual environment) but I am not using virtualenvwrapper.


Solution

  • Thank you to @Mofi for many possible things to try in the comments section!

    The gotcha was in first comment linking to here (placement of "" around the environment variable): https://stackoverflow.com/a/26388460/11163122

    REM TODO: figure out why Python can't see this
    SET MY_ENV_VAR="foo"
    
    REM DONE: this works (quotes on outside)
    SET "MY_ENV_VAR=foo"
    

    It seems the venv activation was not clobbering preexisting environment variables, as @JohnGordon speculated in the comments.

    When pip installed on Windows, the run_python_console_script Entry Point is installed into the venv as venv\Scripts\run_python_console_script.exe.