[파이썬] os 환경 변수 설정: `os.putenv()`

What are Environment Variables?

Environment variables are essentially key-value pairs that hold information about the environment in which a program is running. They are used to store system-wide configuration settings, paths to executable files, and other important information that can be accessed by programs.

The values of environment variables can be accessed by the programs running on the operating system. For example, the PATH environment variable stores a list of directories where the operating system looks for executable files. When you run a command in the terminal, the operating system checks the PATH variable to find the location of the executable.

Using os.putenv()

Python provides the os.putenv() function to set environment variables. The putenv() function takes two arguments: the name of the environment variable and its value.

Here is an example of how to use os.putenv():

import os

# Set the value of an environment variable
os.putenv("API_KEY", "your_api_key")

# Get the value of an environment variable
api_key = os.getenv("API_KEY")
print(api_key)

In the example above, we set the value of the API_KEY environment variable using os.putenv(). We can then retrieve the value of the environment variable using os.getenv().

Note on Mutable Environment Variables

It’s important to note that not all operating systems support mutable environment variables. Some operating systems, like Windows, do not support changing the value of an environment variable once it is set. In such cases, the os.putenv() function may not have any effect. In these cases, it is recommended to use the os.environ dictionary to set environment variables instead.

Conclusion

In this blog post, we have explored how to set environment variables using os.putenv() in Python. Environment variables are an important aspect of the operating system environment, and being able to modify them programmatically can be useful in various scenarios.

Remember to use the os.putenv() function responsibly, as modifying environment variables can have system-wide effects.