【问题标题】:os.environ.get returns None when called from a different .py file当从不同的 .py 文件调用时,os.environ.get 返回 None
【发布时间】:2022-12-09 04:41:13
【问题描述】:

我有一个函数 set_env_vars(),当从一个文件调用时,它工作正常,当从另一个文件调用时,返回 None

杂项.py

import os


def set_env_vars(test):

    print(f"test = {test}")
    if test:
        api_name = os.environ.get("TAPI_NAME")
        api_key = os.environ.get("TAPI_KEY")
        api_passphrase = os.environ.get("TAPI_PASSPHRASE")
        api_secret = os.environ.get("TAPI_SECRET")
        url = "https://openapi-sandbox.kucoin.com/api/v1/accounts"
    else:
        api_name = os.environ.get("API_NAME")
        api_key = os.environ.get("API_KEY")
        api_passphrase = os.environ.get("API_PASSPHRASE")
        api_secret = os.environ.get("API_SECRET")
        url = "https://api.kucoin.com/api/v1/accounts"
    return api_name, api_key, api_passphrase, api_secret, url

另一个.py

import misc

test = False

api_name, api_key, api_passphrase, api_secret, url = misc.set_env_vars(test)

print(api_name, api_key, api_passphrase, api_secret, url)
exit()

输出:

test = False

None None None None https://api.kucoin.com/api/v1/accounts

getbalance.py

import misc

test = False

api_name, api_key, api_passphrase, api_secret, url = misc.set_env_vars(test)

print(api_name, api_key, api_passphrase, api_secret, url)
exit()

输出:

test = False

APIname 63key011... APIpassphrase API-secret-31c... https://api.kucoin.com/api/v1/accounts

换句话说,两个文件/调用是相同的,但只有 getbalance.py 有效。为什么?我在这里错过了什么? 谢谢

【问题讨论】:

  • 我敢打赌您的 IDE/... 的设置方式会根据您运行的入口点传递不同的环境变量。
  • 你是如何执行这些的?
  • 这些文件在同一个文件夹中吗?例如在 VS 代码中运行一个文件夹中的所有内容....
  • 这些文件位于同一文件夹中,要运行它们,我转到文件 Ctrl+Shift+F10,至于 IDE 设置,入口点将是我正在运行的文件(这是我的假设),我不仅仅因为您从不同的文件进行调用,就可以了解系统调用的行为方式有何不同。

标签: python


【解决方案1】:

谢谢 AKX,你是对的,入口点查找它自己的 venv 变量,因此如果运行不同的程序你必须创建新的 env 变量

【讨论】:

    猜你喜欢
    • 2022-01-26
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2020-01-18
    相关资源
    最近更新 更多