Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Subprocess Does not Get Environment Variable from Bat File

I have a bat file that sets some environment variables such as

@echo off
SET MY_ENV_VAR=C:\temp

I would like to run this bat file via Python and run other executables that depend on this environment variable bat sets. But even if the bat file runs, I cannot see the environment variables via Python

subprocess.call(['path_to_bat_file\file.bat'], shell = False)
print(os.environ['MY_ENV_VAR'])

I tried to set Shell to True and add other parameters I found on the internet but nothing was successfull. It gives KeyError on os.environ that MY_ENV_VAR is not found. When I run the bat file manually before running the python script, everything works as expected.

Any help is appreciated.

Thank you,

like image 981
MeCe Avatar asked Jan 24 '26 03:01

MeCe


1 Answers

There is no way to change your environment from a child process. The end :)

But you can change the environment variable from within a script like,

import os
os.environ["MY_ENV_VAR"] = "C:\temp"
like image 133
han solo Avatar answered Jan 26 '26 15:01

han solo