![](/img/trans.png)
[英]Python subprocess export environment variables (which use other environment variable)
[英]Use environment variable in python command
我有一個 Python 腳本,用於詢問連接到 Raspberry Pi 的熱電偶 HAT。 我現在正在嘗試使用 .env 文件,以便可以跨多個系統使用相同的腳本。
我對在方法中使用環境變量的一段代碼有疑問(抱歉,不確定這是否是正確的術語)。
這是我嘗試添加環境變量之前的代碼:
from dotenv import load_dotenv #.env files
from pathlib import Path #.env files
import os
env_path = Path(os.path.expanduser('PATH/HERE/.env'))
load_dotenv(dotenv_path=env_path)
for a in range(number_of_tcHATs):
hat_list.append([])
hat_list[a]=daqhats.mcc134(a)
for x in range(int(os.getenv('NUMBER_OF_THERMOCOUPLES'))):
hat_list[a].tc_type_write(x,daqhats.TcTypes.TYPE_N)
我正在使用的更新代碼是(僅最后一行更改):
from dotenv import load_dotenv #.env files
from pathlib import Path #.env files
import os
env_path = Path(os.path.expanduser('PATH/HERE/.env'))
load_dotenv(dotenv_path=env_path)
for a in range(number_of_tcHATs):
hat_list.append([])
hat_list[a]=daqhats.mcc134(a)
for x in range(int(os.getenv('NUMBER_OF_THERMOCOUPLES'))):
print("hat_list[" + str(a) + "].tc_type_write(" + str(x) + ",daqhats.TcTypes."+ os.getenv('THERMOCOUPLE_TYPE') +")")
當我在屏幕上看到以下內容時,來自 .env 和連接的拉動起作用:
hat_list[0].tc_type_write(0,daqhats.TcTypes.TYPE_N)
hat_list[0].tc_type_write(1,daqhats.TcTypes.TYPE_N)
hat_list[0].tc_type_write(2,daqhats.TcTypes.TYPE_N)
hat_list[0].tc_type_write(3,daqhats.TcTypes.TYPE_N)
hat_list[1].tc_type_write(0,daqhats.TcTypes.TYPE_N)
hat_list[1].tc_type_write(1,daqhats.TcTypes.TYPE_N)
hat_list[1].tc_type_write(2,daqhats.TcTypes.TYPE_N)
hat_list[1].tc_type_write(3,daqhats.TcTypes.TYPE_N)
但它從不運行代碼本身。 我怎樣才能做到這一點?
再次閱讀我的評論,根據入門,您缺少load_dotenv()
調用。 僅僅導入它是不夠的,你需要調用它。 沒有它, os.getenv()
只會從操作系統環境返回變量,因此不知道任何 .env 文件。
from dotenv import load_dotenv
load_dotenv() # take environment variables from .env.
# Code of your application, which uses environment variables (e.g. from `os.environ` or
# `os.getenv`) as if they came from the actual environment.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.