简体   繁体   English

Python中是否有等效的NODE_ENV

[英]Is there a NODE_ENV equivalent in Python

Is there a NODE_ENV equivalent in Python? Python中是否有等效的NODE_ENV?

I want to dynamically load JSON configurations to the python application based on the executing environment. 我想根据执行环境将JSON配置动态加载到python应用程序。 In nodeJs, I do this by using the process.env.NODE_ENV. 在nodeJs中,我通过使用process.env.NODE_ENV来执行此操作。

For example, 例如,

I start the app like this, 我这样启动应用程序

NODE_ENV=production node server.js

And use the variable in the application like this, 并像这样在应用程序中使用变量,

if(process.env.NODE_ENV == "production") {
    // Load the production config file here (eg: database.json)
} else {
    // Load the development config file here (located in a different directory)
}

How can I achieve the same in Python? 如何在Python中实现相同目标? Or can I make use of python virtualenv or python setuptools to have a workaround? 或者我可以利用python virtualenv或python setuptools来解决问题吗?

For starters, you could do something like this. 对于初学者,您可以执行以下操作。

import os
env = os.environ.get("PYTHON_ENV")
if(env =="production"):
   //
else :

The script can be run with PYTHON_ENV="production" python myscript.py . 可以使用PYTHON_ENV="production" python myscript.py运行脚本。 Or you could use some library like dotenv( https://github.com/theskumar/python-dotenv ). 或者您可以使用诸如dotenv( https://github.com/theskumar/python-dotenv )之类的库。

您可以在python pip install environs 尝试environs库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM