How to set environment variables using python in Windows/Linux?

  • 9 months ago
Comment

ChatGPT
1 / 1

You can set environment variables using Python on both Windows and Linux using different approaches. Here are examples for both platforms:

Windows:

  1. Using the os module:
python
import os

# Set environment variable
os.environ['MY_VARIABLE'] = 'my_value'

# Access environment variable
print(os.environ['MY_VARIABLE'])

Linux:

  1. Using the os module:
python
import os

# Set environment variable
os.environ['MY_VARIABLE'] = 'my_value'

# Access environment variable
print(os.environ['MY_VARIABLE'])
  1. Using export command (Linux shell command):
python
import subprocess

# Set environment variable using export command
subprocess.call(["export", "MY_VARIABLE=my_value"], shell=True)

# Access environment variable
result = subprocess.check_output(["echo", "$MY_VARIABLE"], shell=True)
print(result.decode('utf-8').strip())

Keep in mind that when using the os module to set environment variables, the changes are limited to the current Python process. If you want to set environment variables globally for the entire system, you'll need to use platform-specific methods outside of Python (e.g., Windows Environment Variables dialog or shell commands on Linux).

Note: In Linux, the export command is a shell command, so using it in the context of a Python script may not have the same effect as using it directly in the shell. The example above demonstrates how you might use the export command within a Python script, but it's generally recommended to manage environment variables through the operating system's built-in mechanisms.