繁体   English   中英

我们可以从 ~/.bash_profile 加载环境变量而不必源 ~./bash_profile 吗?

[英]Can we load environment variables from ~/.bash_profile without having to source ~./bash_profile?

我有一个名为scraper.py的 python 脚本,它在某些日子从网络上抓取信息。 这些天我用cronjob自动化了这个脚本来运行。 现在每次脚本运行时,我都想向 Slack 发送通知以确保抓取成功。 所以我创建了一个不同的脚本helper_functions.py ,它具有向 Slack 发送消息的功能。 现在,因为我使用了一个无法在脚本中共享的API_KEY ,因为我将它推送到了 GitHub,所以我将它存储在~./.bash_profile 如果我从终端执行source ~/.bash_profile ,脚本运行得非常好,但是当我关闭会话时,代码会中断。 那么有没有办法让它在不采购 bash 文件夹的情况下工作?

以下是scraper.py的脚本

import datetime
import helper_functions as hf


hf.slack_msg("Start scrape")

class IndexSpider(scrapy.Spider):
    name = "index"
    start_urls = [
        "https://finance.yahoo.com"
    ]

    def parse(self, response):
        index = response.css("span.Trsdu\(0\.3s\)::text").getall()
        yield {
            'datetime'          : datetime.datetime.now().strftime("%Y-%m-%d %X"),
            's&p_500'           : index[0],
            's&p_500_delta'     : index[1],
            's&p_500_delta(%)'  : index[2],
            'dow_30'            : index[3],
            'dow_30_delta'      : index[4],
            'dow_30_delta(%)'   : index[5],
            'nasdaq'            : index[6],
            'nasdaq_delta'      : index[7],
            'nasdaq_delta(%)'   : index[8],
        }

hf.slack_msg("End scrape")

helper_functions.py

import json
import os

def slack_msg(msg):

    data = {
        "text" : msg
    }

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

这是一个想法:

  • 将令牌放在自己的文件中,例如 ~/.secrets/slack_api_key.txt
  • 修改 ~/.bash_profile 做export SLACK_API_KEY=$(cat ~/.secrets/slack_api_key.txt)
  • 修改 helper_functions.py 做webhook = os.environ.get("SLACK_API_KEY") or open(os.path.expanduser("~/.secrets/slack_api_key.txt")).read().strip() ,这将首先查找环境变量,如果未定义变量,则回退到读取文件

crontab 中的活动行将是环境设置或 cron 命令。 环境设置的形式是,

     name = value

所以你可以添加

SLACK_API_KEY='theapikey'

* * * * * scraper.py

暂无
暂无

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

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