簡體   English   中英

vscode/Python | 無法訪問環境變量

[英]vscode/Python | unable to acess environment variables

所以基本上我的問題是我不知道為什么我不能訪問我在 my.env 文件中設置的環境變量。 我很確定我已經正確設置了它,因為 AERPL 產生了正確的 output,但是當我使用我的終端(Git-bash)或代碼運行器時,它們無法訪問環境變量並且只是吐出一個錯誤。 我在網上做了很多搜索,但對於我的生活,我無法弄清楚為什么它不起作用。 我敢肯定有一些簡單的修復方法,我不知何故錯過了......但如果有人能弄清楚它為什么不起作用,請告訴我。 先感謝您!


文件結構

cwd/
    .vscode/
        settings.json
    env/
        Lib/
        Scripts/
        .env
    testenv.py

設置.json

{
    "python.testing.promptToConfigure": false,
    "python.testing.pytestEnabled": false,
    "python.testing.unittestEnabled": false,
    "python.testing.nosetestsEnabled": false,
    "python.pythonPath": "${workspaceFolder}\\env\\Scripts\\python.exe", // Python 3.8.2
    "python.envFile": "${workspaceFolder}\\env\\.env",
    "python.formatting.provider": "autopep8",
    "editor.formatOnSave": true,
    "python.linting.enabled": true,
    "code-runner.executorMap": {
        "python": "$pythonPath -u $fullFileName"
    },
    "code-runner.clearPreviousOutput": true,
    "code-runner.showExecutionMessage": true
} 

.env

TEST = "test"

測試環境.py

import os
print(os.getenv('TEST'))
print("==========")
print(os.environ['TEST'])

代碼運行器/集成終端 Output:

os.getenv: None
==========
Traceback (most recent call last):
  File "c:\test\testenv.py", line 4, in <module>
    print(f"os.environ: {os.environ['TEST']}")
  File "c:\python38\lib\os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'TEST'

$ py testenv.py
os.getenv: None
==========
Traceback (most recent call last):
  File "testenv.py", line 4, in <module>
    print(f"os.environ: {os.environ['TEST']}")
  File "c:\python38\lib\os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'TEST'

AEREPL Output

Print Output:
os.getenv: test
==========
os.environ: test
Variables:
{}

您可以通過 VSCode 強制識別集成終端中的環境變量,而無需進入調試模式。 此示例適用於 Linux 和 bash。

  • 找到參數terminal.integrated.profiles.linux
  • 添加到 settings.json,更正實際.env 文件和 shell 的路徑:
        "bash-env": {
            "path": "bash",
            "icon": "terminal-bash",
            "args": ["-c", "if [ -f .env ]; then export $(cat .env); fi; if [ -f .vscode/.env ]; then export $(cat .vscode/.env); fi; bash"]
        },
  • 找到參數terminal.integrated.defaultProfile.linux
  • 選擇配置文件bash-env

這個例子的靈感來自問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM