简体   繁体   中英

Cannot read environment variable set with PowerShell with os.environ.get

A bit of a random problem here. I set an environment variable using PowerShell like this:

$env:GOOGLE_ELEVATION_API="the_api-key"

Then in python I attempt to read it with this simple script:

from os import environ

key = environ.get("GOOGLE_ELEVATION_API")

This returns None . If I query my environment variables in PowerShell it is there. If I query it through python with os.environ it is not.

None of the results I found make reference that this should be an issue, neither on the PowerShell side nor on python's side. I have not restarted my machine since I honestly do not believe this is what should be done. I did restart my IDE in the hope that it is somehow caching the environment but thankfully it does not.

Any pointers would be great!

  • Setting an environment variable via PowerShell's $env: namespace defines it for the current process only .

    • Any Python scripts invoked directly from a PowerShell session would see such variables, however, because child processes inherit the caller's environment variables.
  • To persistently define a Windows environment variable at the machine level that all processes see, you must use .NET APIs directly (as of PowerShell 7.1):

# Note: Requires ELEVATION, due to setting at the *machine* level.
[Environment]::SetEnvironmentVariable('GOOGLE_ELEVATION_API', 'the_api-key', 'Machine')

Note that only future PowerShell sessions will see this variable, and the need to restart an application in order for it to see the new variable typically also applies to other running applications.

(The exception are those applications that actively listen for the WM_SETTINGCHANGE message and refresh their environment in response, which is what the Windows GUI shell ( explorer.exe ) does.)

For more information about persistently setting environment variables on Windows, see this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM