How to set environment variables in Python?

前端 未结 11 2022
情话喂你
情话喂你 2020-11-22 04:00

I need to set some environment variables in the Python script and I want all the other scripts that are called from Python to see the environment variables\' set.

If

11条回答
  •  梦谈多话
    2020-11-22 04:17

    You may need to consider some further aspects for code robustness;

    when you're storing an integer-valued variable as an environment variable, try

    os.environ['DEBUSSY'] = str(myintvariable)
    

    then for retrieval, consider that to avoid errors, you should try

    os.environ.get('DEBUSSY', 'Not Set')
    

    possibly substitute '-1' for 'Not Set'

    so, to put that all together

    myintvariable = 1
    os.environ['DEBUSSY'] = str(myintvariable)
    strauss = int(os.environ.get('STRAUSS', '-1'))
    # NB KeyError <=> strauss = os.environ['STRAUSS']
    debussy = int(os.environ.get('DEBUSSY', '-1'))
    
    print "%s %u, %s %u" % ('Strauss', strauss, 'Debussy', debussy)
    

提交回复
热议问题