django os.environ caution setdefault operating environment variables

In most cases, if you need to set the environment variable in the program is running, use os.environ.setdefault function is no problem, but there are two scenarios under setdefault cause unexpected problems, need to be used with caution:

If before the program execution, a system has existed for environment variables (e.g. ENV = VAL1), at this time if a different set of values (e.g., VAL2) the procedures used setdefault function environment variables that are characteristic as a function of setdefault cause can not be set to a new value
but also because of the above that, if the process a first set environment variables (such as ENV = VAL1), and a starts the child process B, the child process B inherits a process of all the environmental variables will lead to when B is running, the program execution environment ENV environmental variables already present, if at this time resulting in a different set of values (e.g., VAL2) the environment variables setdefault functions, also for the same reason can not be set to a new value
so set the system environment variables in the program run safest method is:

os.environ [ENV '] =' VAL '

 

python acquisition system environment variables os.environ and os.putenv
talk "if" BATCH_CONFIG_INI from one segment code "in os.environ:" environment variable value determination are not defined

If the value of the environment variable definition, then go, otherwise take config.ini file in the current directory.

复制代码
if "BATCH_CONFIG_INI" in os.environ:
print "Using custom ini file!"
self.inifile = os.environ["BATCH_CONFIG_INI"]
else:
self.inifile = self.cur_file_dir() + "/config.ini"
self.db_print ("inifile = (%s)" %(self.inifile))
复制代码

The method used to set or get Python Shell environment variables:

First, set the system environment variables

1, os.environ [ 'environment variable name'] = "environment variable" # wherein both the key and value string type

2, os.putenv ( 'environment variable name', 'environment variable')

 

Second, the acquisition system environment variables

1, os.environ [ 'environment variable name']

2, os.getenv ( 'environment variable name')

 

 

celery created in the client's file main:

from celery  import Celery

os Import
# Configure celery go there if you need to load a configuration file
os.environ.setdefault ( "DJANGO_SETTINGS_MODULE", "settings.dev ")

# 1. Create celery client
celery_app = Celery ( '')

# 2 loading configuration information
celery_app.config_from_object ( 'celery_tasks.config')
# 3. Register asynchronous tasks (those tasks can enter the task queue)
celery_app.autodiscover_tasks ([ 'celery_tasks.sms',' celery_tasks.email ',' celery_tasks .html '])

Guess you like

Origin www.cnblogs.com/bufufan/p/11106250.html