繁体   English   中英

.bash_profile 中是否有特定的存储环境变量的格式?

[英]Is there a specific format of storing environment variables in .bash_profile?

以下是我用来向 slack 发送消息的 python 代码。 当我尝试从环境中获取 api_key 时,以下代码会引发错误,但是当我用实际的 API 密钥替换webhook时,它运行得非常好。

import requests
import json
import os

data = {
    "text" : "hi there"
}

webhook = os.environ.get("SLACK_API_KEY")
requests.post(webhook, json.dumps(data))

SLACK_API_KEY是我存储在系统的.bash_profile文件夹中的环境变量。 API 密钥的格式如下: https://hooks.slack.com/services/alpha_numeric/alpha_numeric/alpha_numeric : https://hooks.slack.com/services/alpha_numeric/alpha_numeric/alpha_numeric

这是我在 .bash_profile 文件夹中存储 API 密钥的方式:

export SLACK_API_KEY="https://hooks.slack.com/services/alpha_numeric/alpha_numeric/alpha_numeric"

这是我尝试从环境中导出 api_key 时出现的错误。

Traceback (most recent call last):
  File "/Users/nikhilsawal/OneDrive/investment_portfolio/helper_functions.py", line 10, in <module>
    requests.post(webhook, json.dumps(data))
  File "/Users/nikhilsawal/OneDrive/investment_portfolio/track_proj/lib/python3.8/site-packages/requests/api.py", line 119, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/Users/nikhilsawal/OneDrive/investment_portfolio/track_proj/lib/python3.8/site-packages/requests/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "/Users/nikhilsawal/OneDrive/investment_portfolio/track_proj/lib/python3.8/site-packages/requests/sessions.py", line 516, in request
    prep = self.prepare_request(req)
  File "/Users/nikhilsawal/OneDrive/investment_portfolio/track_proj/lib/python3.8/site-packages/requests/sessions.py", line 449, in prepare_request
    p.prepare(
  File "/Users/nikhilsawal/OneDrive/investment_portfolio/track_proj/lib/python3.8/site-packages/requests/models.py", line 314, in prepare
    self.prepare_url(url, params)
  File "/Users/nikhilsawal/OneDrive/investment_portfolio/track_proj/lib/python3.8/site-packages/requests/models.py", line 388, in prepare_url
    raise MissingSchema(error)
requests.exceptions.MissingSchema: Invalid URL 'None': No schema supplied. Perhaps you meant http://None?
[Finished in 0.149s]

您的 env var 是否存储正确,要检查您的环境变量,您可以执行以下操作:在 shell 中echo $SLACK_API_KEY或者您可以在它之后执行env和 grep 。

注意~/.bash_profile如果对于用户特定的设置和操作(仅限登录 shell),或者有.bashrc为交互式非登录 shell 执行。

我建议将您的变量放在~/.profile ,然后不要忘记source ~/.profile或您决定放置 env variable 的任何地方。

如果它们不存在,您可以创建它们,我推荐这篇文章来解释差异。

您也可以直接从脚本设置 var it:

os.environ["SLACK_API_KEY"] = "value"

~/.bash_profile为你的案例做了一个小测试: 在此处输入图片说明

暂无
暂无

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

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