简体   繁体   English

Python和macOS如何使用.env文件和环境变量

[英]How to use .env files and environment variables with Python and macOS

So I am connecting to an RPC cloud-node and trying to get the latest block from the Ethereum blockchain, along with all the block details and have written some code in python using web3.py.所以我正在连接到一个 RPC 云节点并尝试从以太坊区块链获取最新的块,以及所有块的详细信息,并使用 web3.py 在 python 中编写了一些代码。 I have the code ready and according to the official doc https://web3py.readthedocs.io/en/v5/troubleshooting.html , I am able to setup a virtual environment too.我已经准备好代码,根据官方文档https://web3py.readthedocs.io/en/v5/troubleshooting.html ,我也可以设置虚拟环境。 I only want to understand how to add environment variables and then revoke them in my code.我只想了解如何添加环境变量,然后在我的代码中撤销它们。 As far as I understand I will have to import os and then create a file with.env and type据我所知,我将不得不导入 os 然后创建一个文件 with.env 并输入

username=xyz
key=abc
endpoint="example.com"

Is that it?是吗?

The easiest way to have environment variables on macOS is to use Bash shell environment files and source command .在 macOS 上拥有环境变量的最简单方法是使用Bash shell 环境文件和 source 命令 Virtualenv does this internally when you run the command source venv/bin/activate .当您运行命令source venv/bin/activate时,Virtualenv 在内部执行此操作。

Note that there is no standard on .env file format.请注意, .env文件格式没有标准。

Create an env file mac.env with the content:使用以下内容创建环境文件mac.env

export USERNAME=xyz
export KEY=abc
export ENDPOINT="example.com"

Then in your Bash shell you can import this file before running your Python application:然后在您的 Bash shell 中,您可以在运行 Python 应用程序之前导入此文件:

source mac.env

echo $USERNAME
xyz

Because the .env file is now loaded into the memory of your shell and exported, any Python application you run will automatically receive these environment variables.因为.env文件现在已加载到您的 shell 的 memory 并导出,所以您运行的任何 Python 应用程序将自动接收这些环境变量。

python myapplication.py

Then if your Python code you can do:那么如果你的 Python 代码你可以这样做:

import os

username = os.environ.get("USERNAME")

if username is None:
   raise RuntimeError("USERNAME not set")
else:
   print(f"Username is {username}")

If you need to use different formats of env files, eg for Docker or JavaScript compatibility, there are tools called shdotenv and python-dotenv to deal with this.如果您需要使用不同格式的 env 文件,例如为了 Docker 或 JavaScript 兼容性,可以使用名为shdotenvpython-dotenv的工具来处理这个问题。

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

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