Python: Environment variables
Python Basic: Exercise-53 with Solution
Write a Python program to access environment variables.
Sample Solution-1:
Python Code:
# Import the 'os' module to access operating system-related functionality, including environment variables.
import os
# Print a separator for clarity.
print('*----------------------------------*')
# Print all environment variables.
print(os.environ)
# Print a separator for clarity.
print('*----------------------------------*')
# Access and print the 'HOME' environment variable.
print(os.environ['HOME'])
# Print a separator for clarity.
print('*----------------------------------*')
# Access and print the 'PATH' environment variable.
print(os.environ['PATH'])
# Print a separator for clarity.
print('*----------------------------------*')
Sample Output:
*----------------------------------* environ({'LESSOPEN': '| /usr/bin/lesspipe %s', '_': '/usr/bin/timeout', 'LIBVIRT_DEFAULT_URI': 'qemu:///system ', 'HOME': '/home/students', 'TERM': 'xterm-256color', 'SHELL': '/bin/bash', 'SHLVL': '2', 'USER': 'students', 'MAIL': '/var/mail/students', 'COMP_WORDBREAKS': ' \t\n"\'><;|&(:', 'PATH': '/usr/local/bin:/usr/bin:/bin:/us r/local/games:/usr/games', 'LANG': 'en_US.UTF-8', 'LOGNAME': 'students', 'LS_COLORS': 'rs=0:di=01;34:ln=01;36: mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42 :ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;3 1:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.d z=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01; 31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31: *.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*. bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.p ng=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.m kv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wm v=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01 ;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36 :*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36: *.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:', 'JAVA_HOME': '/usr/lib/jvm/java-7-openjdk-amd 64/jre/bin/java', 'LESSCLOSE': '/usr/bin/lesspipe %s %s', 'PWD': '/home/students'}) *----------------------------------* /home/students *----------------------------------* /usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games *----------------------------------*
Explanation:
The ‘OS’ module provides a portable way of using operating system dependent functionality.
In the above exercise we imports the os module and uses it to print environment variables to the console output.
The environ attribute of the os module is a dictionary-like object that represents the environment variables in the current process. The print() function is used to print the entire dictionary of environment variables to the console using os.environ.
The code then uses square brackets ([]) to access specific environment variables by their names. In this case, it prints the values of the HOME and PATH environment variables to the console using os.environ['HOME'] and os.environ['PATH'], respectively.
Sample Solution-2:
Python Code:
# Import the 'os' module to access operating system-related functionality, including environment variables.
import os
# Iterate through all environment variables in the 'os.environ' dictionary.
for data in os.environ:
# Print the name of the environment variable.
print(data)
# Print a separator for clarity.
print('-' * 15)
# Print the value of the environment variable.
print(os.environ[data])
# Print a line of '=' characters as an additional separator.
print('=' * 30)
Sample Output:
exit_code --------------- 0 ============================== node_version --------------- 8.11.3 ============================== versioning --------------- null ============================== version --------------- 0.0.0 ============================== unstable_restarts --------------- 0 ============================== restart_time --------------- 47 ============================== pm_id --------------- 0 ============================== created_at --------------- 1621962710172 ============================== axm_dynamic --------------- [object Object] ============================== axm_options --------------- [object Object] ============================== axm_monitor --------------- [object Object] ============================== axm_actions --------------- ============================== pm_uptime --------------- 1623108424625 ============================== status --------------- launching ============================== unique_id --------------- f981135a-143b-43bf-8ca1-906432f1f9e1 ============================== PM2_HOME --------------- /root/.pm2 ============================== PM2_INTERACTOR_PROCESSING --------------- true ============================== PM2_DISCRETE_MODE --------------- true ============================== PM2_PROGRAMMATIC --------------- true ============================== PYTHONPATH --------------- /trinket/python3 ============================== MPLBACKEND --------------- module://trinket_backend ============================== TERM --------------- xterm ============================== HOME --------------- /root ============================== LC_ALL --------------- en_US.UTF-8 ============================== LANGUAGE --------------- en_US:en ============================== LANG --------------- en_US.UTF-8 ============================== DEBIAN_FRONTEND --------------- teletype ============================== HOSTNAME --------------- 4735090b6baa ============================== PATH --------------- /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin ============================== NODE_APP_INSTANCE --------------- 0 ============================== vizion_running --------------- false ============================== km_link --------------- false ============================== pm_pid_path --------------- /root/.pm2/pids/shell-0.pid ============================== pm_err_log_path --------------- /dev/null ============================== pm_out_log_path --------------- /dev/null ============================== exec_mode --------------- fork_mode ============================== instances --------------- 1 ============================== exec_interpreter --------------- node ============================== pm_cwd --------------- /trinket-workdir ============================== pm_exec_path --------------- /trinket-workdir/server/python3/shell.js ============================== node_args --------------- ============================== name --------------- shell ============================== env --------------- [object Object] ============================== merge_logs --------------- true ============================== vizion --------------- true ============================== autorestart --------------- true ============================== instance_var --------------- NODE_APP_INSTANCE ============================== pmx --------------- true ============================== automation --------------- true ============================== treekill --------------- true ============================== username --------------- root ============================== windowsHide --------------- true ============================== kill_retry_time --------------- 100 ==============================
Flowchart:
Sample Solution-3:
Python Code:
# Import the 'os' module to access operating system-related functionality, including environment variables.
import os
# Iterate through all environment variables and their values using the 'os.environ.items()' method.
for item, value in os.environ.items():
# Print the environment variable name and its corresponding value.
print('{}: {}'.format(item, value))
Sample Output:
exit_code: 0 node_version: 8.11.3 versioning: null version: 0.0.0 unstable_restarts: 0 restart_time: 21 pm_id: 0 created_at: 1622456136302 axm_dynamic: [object Object] axm_options: [object Object] axm_monitor: [object Object] axm_actions: pm_uptime: 1623107594098 status: launching unique_id: 840ddab5-aa87-4cb5-ab04-16da1d9802f6 PM2_HOME: /root/.pm2 PM2_INTERACTOR_PROCESSING: true PM2_DISCRETE_MODE: true PM2_PROGRAMMATIC: true PYTHONPATH: /trinket/python3 MPLBACKEND: module://trinket_backend TERM: xterm HOME: /root LC_ALL: en_US.UTF-8 LANGUAGE: en_US:en LANG: en_US.UTF-8 DEBIAN_FRONTEND: teletype HOSTNAME: b0e45c20d4ca PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin NODE_APP_INSTANCE: 0 vizion_running: false km_link: false pm_pid_path: /root/.pm2/pids/shell-0.pid pm_err_log_path: /dev/null pm_out_log_path: /dev/null exec_mode: fork_mode instances: 1 exec_interpreter: node pm_cwd: /trinket-workdir pm_exec_path: /trinket-workdir/server/python3/shell.js node_args: name: shell env: [object Object] merge_logs: true vizion: true autorestart: true instance_var: NODE_APP_INSTANCE pmx: true automation: true treekill: true username: root windowsHide: true kill_retry_time: 100
Flowchart:
Python Code Editor:
Previous: Write a Python program to print to stderr.
Next: Write a Python program to get the current username.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/python-basic-exercise-53.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics