Environment variables must be strings, so use

import os
os.environ["DEBUSSY"] = "1"

to set the variable DEBUSSY to the string 1.

To access this variable later, simply use

print(os.environ["DEBUSSY"])

Child processes automatically inherit the environment of the parent process -- no special action on your part is required.

Answer from Sven Marnach on Stack Overflow
🌐
Ask Ubuntu
askubuntu.com β€Ί questions β€Ί 1331463 β€Ί how-to-make-an-environment-variable-available-for-a-python-program-using-os-envi
How to make an environment variable available for a python program using os.environ module? - Ask Ubuntu
April 15, 2021 - ... When using pycharm, the environment variables have to be defined in "Run/Debug Configurations" dialog. In the python configuration inside the region "Environment" you can define environment variables that are passed to the program.
Discussions

export - set environment variable in python script - Stack Overflow
I have a bash script that sets an environment variable an runs a command LD_LIBRARY_PATH=my_path sqsub -np $1 /homedir/anotherdir/executable Now I want to use python instead of bash, because I wan... More on stackoverflow.com
🌐 stackoverflow.com
bash - Set environment variables in a python script and use them in a chained call - Unix & Linux Stack Exchange
I would like to set a couple of environment variables in a Python script, then use said environment variables in a chained call. For example, a python script called set_env.py: os.environ["MY_... More on unix.stackexchange.com
🌐 unix.stackexchange.com
August 28, 2024
python - PYTHONPATH on Linux - Stack Overflow
PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. More on stackoverflow.com
🌐 stackoverflow.com
linux - set environment variables by file using python - Stack Overflow
I want set these environment variables by reading from file . how can i do this in python More on stackoverflow.com
🌐 stackoverflow.com
🌐
Tutorialspoint
tutorialspoint.com β€Ί python β€Ί python_environment.htm
Python - Environment Setup
Here are important environment variables, which can be recognized by Python βˆ’ Β· There are three different ways to start Python βˆ’ Β· You can start Python from Unix, DOS, or any other system that provides you a command-line interpreter or shell window. Enter python the command line. Start coding right away in the interactive interpreter. $python # Unix/Linux or python% # Unix/Linux or C:> python # Windows/DOS
🌐
Vonage
developer.vonage.com β€Ί en β€Ί blog β€Ί python-environment-variables-a-primer
Python Environment Variables (Env Vars): A Primer
Learn how to use Python environment variables with os.environ, os.getenv, and .env files. Secure your API keys, set variables in Linux, and make your code safer and more adaptable.
🌐
Enterprise DNA
blog.enterprisedna.co β€Ί python-set-environment-variable
Python: Set Environment Variable (Explained) – Master Data Skills + AI
set PYTHONPATH=C:\path\to\your\python\directory echo %PYTHONPATH% ... To list all environment variables, you can simply run the set command in the terminal. In Unix-based operating systems such as Linux and MacOS, the export command is used to set environment variables.
🌐
TutorialsPoint
tutorialspoint.com β€Ί article β€Ί how-to-set-python-environment-variable-pythonpath-on-linux
How to set Python environment variable PYTHONPATH on Linux?
2 weeks ago - This command sets the PYTHONPATH environment variable to /home/user/myproject and also includes the previous value of PYTHONPATH in case it was already set. Note that the path should be separated by a colon (:) on Linux.
🌐
CodingNomads
codingnomads.com β€Ί blog β€Ί python-environment-variables-set-a-variable-in-bash
Python Environment Variables: Set a Variable in Bash
In this blog you will learn how to keep your secrets safe using Python and environment variables in Bash and Python virtual environments. By the end you will know how to: ... Automatically set and unset these virtual environment variables when you activate or deactivate your virtual environment
Find elsewhere
🌐
Linux Hint
linuxhint.com β€Ί set-environment-variables-python
How to get and set environment variables in Python – Linux Hint
The os module will require to import to read the environment variables. The os.environ object is used in Python to access the environment variable. The coder can set and get the value of any environment variable by using this object.
🌐
Real Python
realpython.com β€Ί add-python-to-path
How to Add Python to PATH – Real Python
January 30, 2023 - In this tutorial, you'll learn about how to add Python, or any other program, to your PATH environment variable. You'll be covering the procedure in Windows, macOS, and Linux and find out what PATH is and why it's important.
Top answer
1 of 3
118

bash:

LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable

Similar, in Python:

import os
import subprocess
import sys

os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
                      env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))
2 of 3
26

There are many good answers here but you should avoid at all cost to pass untrusted variables to subprocess using shell=True as this is a security risk. The variables can escape to the shell and run arbitrary commands! If you just can't avoid it at least use python3's shlex.quote() to escape the string (if you have multiple space-separated arguments, quote each split instead of the full string).

shell=False is always the default where you pass an argument array.

Now the safe solutions...

Method #1

Change your own process's environment - the new environment will apply to python itself and all subprocesses.

os.environ['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Method #2

Make a copy of the environment and pass is to the childen. You have total control over the children environment and won't affect python's own environment.

myenv = os.environ.copy()
myenv['LD_LIBRARY_PATH'] = 'my_path'
command = ['sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command, env=myenv)

Method #3

Unix only: Execute env to set the environment variable. More cumbersome if you have many variables to modify and not portabe, but like #2 you retain full control over python and children environments.

command = ['env', 'LD_LIBRARY_PATH=my_path', 'sqsub', '-np', var1, '/homedir/anotherdir/executable']
subprocess.check_call(command)

Of course if var1 contain multiple space-separated argument they will now be passed as a single argument with spaces. To retain original behavior with shell=True you must compose a command array that contain the splitted string:

command = ['sqsub', '-np'] + var1.split() + ['/homedir/anotherdir/executable']
🌐
Stack Exchange
unix.stackexchange.com β€Ί questions β€Ί 782648 β€Ί set-environment-variables-in-a-python-script-and-use-them-in-a-chained-call
bash - Set environment variables in a python script and use them in a chained call - Unix & Linux Stack Exchange
August 28, 2024 - Since python runs in a child process of the shell it can't directly alter the shell's environment variables. However, your python script can output proper shell commands that can be evaluated in the shell. $ python ./set_env.py MY_VAR="x y z";MY_VAR2="a b c"
🌐
Dagster
dagster.io β€Ί blog β€Ί python-environment-variables
Best Practices for Python Env Variables
You might type a command like python my_script.py to run a Python script, or ls (on Linux or Mac) or dir (on Windows) to list the files in the current directory. These are all examples of interacting with a command-line shell. Shell configuration files are special files that the shell reads when it starts up. As a Dagster data engineer, you will probably use them to set environment variables that should be available every time you open a new terminal window.
Top answer
1 of 3
73
  1. PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. e.g.:

    # make python look in the foo subdirectory of your home directory for   
    # modules and packages 
    export PYTHONPATH=${PYTHONPATH}:${HOME}/foo 
    

    Here I use the sh syntax. For other shells (e.g. csh,tcsh), the syntax would be slightly different. To make it permanent, set the variable in your shell's init file (usually ~/.bashrc).

  2. Ubuntu comes with python already installed. There may be reasons for installing other (independent) python versions, but I've found that to be rarely necessary.

  3. The folder where your modules live is dependent on PYTHONPATH and where the directories were set up when python was installed. For the most part, the installed stuff you shouldn't care about where it lives -- Python knows where it is and it can find the modules. Sort of like issuing the command ls -- where does ls live? /usr/bin? /bin? 99% of the time, you don't need to care -- Just use ls and be happy that it lives somewhere on your PATH so the shell can find it.

  4. I'm not sure I understand the question. 3rd party modules usually come with install instructions. If you follow the instructions, python should be able to find the module and you shouldn't have to care about where it got installed.

  5. Configure PYTHONPATH to include the directory where your module resides and python will be able to find your module.

2 of 3
46
  1. PYTHONPATH is an environment variable
  2. Yes (see https://unix.stackexchange.com/questions/24802/on-which-unix-distributions-is-python-installed-as-part-of-the-default-install)
  3. /usr/lib/python2.7 on Ubuntu
  4. you shouldn't install packages manually. Instead, use pip. When a package isn't in pip, it usually has a setuptools setup script which will install the package into the proper location (see point 3).
  5. if you use pip or setuptools, then you don't need to set PYTHONPATH explicitly

If you look at the instructions for pyopengl, you'll see that they are consistent with points 4 and 5.

🌐
FastAPI
fastapi.tiangolo.com β€Ί environment-variables
Environment Variables - FastAPI
You could also create environment variables outside of Python, in the terminal (or with any other method), and then read them in Python. ... The second argument to os.getenv() is the default value to return. If not provided, it's None by default, here we provide "World" as the default value to use. ... // Here we don't set the env var yet $ python main.py // As we didn't set the env var, we get the default value Hello World from Python // But if we create an environment variable first $ export MY_NAME="Wade Wilson" // And then call the program again $ python main.py // Now it can read the environment variable Hello Wade Wilson from Python
🌐
AskPython
askpython.com β€Ί home β€Ί environment variables in python – read, print, set
Environment Variables in Python - Read, Print, Set - AskPython
February 16, 2023 - Environment Variables in Python can be accessed using os.environ object. Read, print and set python environment variables, environment variable exists.
🌐
Python
docs.python.org β€Ί 3 β€Ί using β€Ί cmdline.html
1. Command line and environment β€” Python 3.14.3 documentation
If this option is given, the first element of sys.argv will be the full path to the module file (while the module file is being located, the first element will be set to "-m"). As with the -c option, the current directory will be added to the start of sys.path. -I option can be used to run the script in isolated mode where sys.path contains neither the current directory nor the user’s site-packages directory. All PYTHON* environment variables are ignored, too.
🌐
Medium
medium.com β€Ί @haroldfinch01 β€Ί how-to-set-environment-variables-in-python-ee16132ca524
How to set environment variables in Python? | by Harold Finch | Medium
January 28, 2025 - Open Environment Variables from the System Properties. Add a new variable under System variables or User variables. Use .env Files: This keeps sensitive information out of your codebase and makes configuration easy to manage.