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

Time:05-28

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.

CodePudding user response:

From https://ss64.com/nt/set.html

Changes made using the SET command are NOT permanent, they apply to the current CMD prompt only and remain only until the CMD window is closed.

To permanently change a variable at the command line use SetX

CodePudding user response:

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.


@Mofi to answer your other questions:

PS C:\path> reg QUERY "HKLM\Software\Microsoft\Command Processor" /v AutoRun


ERROR: The system was unable to find the specified registry key or value.
PS C:\path> reg QUERY "HKCU\Software\Microsoft\Command Processor" /v AutoRun
ERROR: The system was unable to find the specified registry key or value.
PS C:\path> .\venv\Scripts\activate
(venv) PS C:\path> reg QUERY "HKLM\Software\Microsoft\Command Processor" /v AutoRun


ERROR: The system was unable to find the specified registry key or value.
(venv) PS C:\path> reg QUERY "HKCU\Software\Microsoft\Command Processor" /v AutoRun
ERROR: The system was unable to find the specified registry key or value.

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.

  • Related