操作系统环境获取()返回Heroku环境变量的None

2024-05-17 18:22:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过Heroku设置了几个环境变量来访问GrapheneDB实例。当我使用Heroku CLI命令heroku config时,所有环境变量都按预期返回。在

例如,"heroku config"返回:

GRAPHENEDB_BOLT_PASSWORD: some_password   
GRAPHENEDB_BOLT_URL:      bolt://hobby-someletters.dbs.graphenedb.com:24786
GRAPHENEDB_BOLT_USER:     appnumbers  
GRAPHENEDB_URL:           http://appnumbers:some_password@hobby-someletters.dbs.graphenedb.com:24789  
NEO4J_REST_URL:           GRAPHENEDB_URL

但是,当我试图使用os.environ.get()方法访问这些环境变量时,所有三个print语句都返回None,而不是{}返回的所需输出。Python无法访问环境变量。如何让python访问这些文件?在

^{pr2}$

我已尝试使用Acess Heroku variables from Flask中的解决方案 但当我执行命令时: heroku config:pull --overwrite CLI返回 config:pull is not a heroku command.


Tags: comconfigurlherokucli环境变量somepassword
4条回答

因为您正在执行一个命令(而不是env或类似的命令)来获取这些配置变量,这意味着它们很可能不在您的正常环境中,这意味着您无法通过os.environ.get()获取它们。在

您可以做的是从该命令的输出中提取它们(示例python 2.7假定它们出现在stdout上,如果它们没有以相同的方式检查stderr):

from subprocess import Popen, PIPE

graphenedb_url = graphenedb_user = graphenedb_pass = None
stdout, stderr = Popen(['heroku', 'config'], stdout=PIPE, stderr=PIPE).communicate()
for line in stdout.split('\n'):
    split = line.split(':')
    if len(split) == 2:
        if split[0] == 'GRAPHENEDB_BOLT_URL':
            graphenedb_url = split[1].strip()
        elif split[0] == 'GRAPHENEDB_BOLT_USER':
            graphenedb_user = split[1].strip()
        elif split[0] == 'GRAPHENEDB_BOLT_PASSWORD':
            graphenedb_pass = split[1].strip()
print graphenedb_url
print graphenedb_user
print graphenedb_pass

注意事项:

  • 示例是python2.7
  • 它假设信息在stdout上显示,如果不检查stderr,也以同样的方式
  • 您可能需要使用heroku可执行文件的完整路径,不确定。在

相关问题 更多 >