bash 如何从python脚本中的.env文件设置环境变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/56520683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 17:07:47  来源:igfitidea点击:

how to set environment variable from .env file in python script?

pythonlinuxbashshellenvironment-variables

提问by Kevin Lee

In the Ubuntu bash shell, I can set the environment variable from the .env file by using command lines "source" (example: source $OCSSWROOT/OCSSW_bash.env).

在 Ubuntu bash shell 中,我可以使用命令行“源”(例如:)从 .env 文件设置环境变量source $OCSSWROOT/OCSSW_bash.env

But sourceis not a function in python. So, how to set an environment variable from the .env file in python?

source不是python中的函数。那么,如何从python中的.env文件中设置环境变量?

'l2gen'is a command line program of SeaDAS which be supported by NASA for processing ocean satellite data. I can run it in the bash shell. now, the more program needs to be coded with python script and 'l2gen' is one of program.

'l2gen' 是 SeaDAS 的命令行程序,由 NASA 支持,用于处理海洋卫星数据。我可以在 bash shell 中运行它。现在,更多的程序需要用 python 脚本编码,'l2gen' 是程序之一。

But the environment variable needs to be set again in python script. According to the google search result, I fond some method to set the environment variable in python. But lacking information about the .env file.

但是需要在python脚本中重新设置环境变量。根据谷歌搜索结果,我喜欢在python中设置环境变量的一些方法。但缺乏有关 .env 文件的信息。

in the Linux bash shell, I set the environment variable by vim and source:

在 Linux bash shell 中,我通过 vim 和 source 设置了环境变量:

    vim .profile
    export OCSSWROOT=[SeaDAS_install_dir]/ocssw (adding this in the profile 
                                                 file and then save/exit)
    source $OCSSWROOT/OCSSW_bash.env

where: SeaDAS_install_dir is the directory where I installed software SeaDAS.

其中: SeaDAS_install_dir 是我安装软件 SeaDAS 的目录。

I try to add the environment variable as following:

我尝试添加环境变量如下:

import subprocess
if __name__=='__main__':
     l2cmdtest = 'l2gen -h'
     new_env = os.environ.copy()
     new_env['OCSSWROOT'] = '/usr/local/seadas-7.5.3/ocssw'
     new_env['OCSSWROOT'] = 'OCSSWROOT/OCSSW_bash.env'
     eturnCodetest = subprocess.call(l2cmdtest, shell=True)

where: 'l2gen -h' is a program which can work in the bash shell.

其中: 'l2gen -h' 是一个可以在 bash shell 中工作的程序。

executing python script, and then an error:

执行python脚本,然后报错:

/bin/sh: 1: l2gen: not found

回答by Mureinik

The python-dotenvpackage can do the heavy lifting for you:

蟒蛇-dotenv包能为你做繁重的工作:

from dotenv import load_dotenv
load_dotenv(dotenv_path='OCSSW_bash.env')