python - Comment accéder aux valeurs variables d'environnement

Mots clés : pythonenvironment-variablespython

meilleur 5 Réponses python - Comment accéder aux valeurs variables d'environnement

vote vote

93

import os print(os.environ['HOME']) 
os.environ 
# using get will return `None` if a key is not present rather than raise a `KeyError` print(os.environ.get('KEY_THAT_MIGHT_EXIST'))  # os.getenv is equivalent, and can also give a default value instead of `None` print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value)) 
import sys print(sys.prefix) 
vote vote

90

'HOME' in os.environ 
print(os.environ.get('HOME', '/home/username/')) 
vote vote

71

try:      os.environ["FOO"] except KeyError:     print "Please set the environment variable FOO"    sys.exit(1) 
vote vote

62

import os  for item, value in os.environ.items():     print('{}: {}'.format(item, value)) 
for i, j in os.environ.items():     print(i, j) 
print(os.environ['HOME']) 
print(os.environ.get('HOME')) 
os.environ['HOME'] = '/new/value' 
vote vote

59

import os print os.environ 

Questions similaires