尝试将 shell 变量导入 python 时如何修复此键错误?

How can I fix this key error when trying to import a shell variable into python?

This 之前有人在这里问过这个问题,但是当我尝试模拟正确答案时,我得到了一个关键错误,我想知道我做错了什么。

我有一个 shell 在主目录中创建目录的脚本:

#!/bin/sh

#choose path to home
directory=~/.some_file

if [ ! -d "$directory" ]
then mkdir "$directory"
fi

#I then export the variable
export directory

然后我转到我的 python 脚本,我想使用我的 shell 脚本中的变量目录作为我的 python 脚本中的相同变量

#!/usr/bin/env python3

import os

variable = os.environ["directory"]
print(variable)

当我 运行 python 文件时出现错误

File "/home/user/import_sh_var.py", line 5, in <module>
variable = os.environ["directory"]
File "/usr/lib/python3.8/os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'directory'

所以我假设我从错误消息中为变量返回 None,但为什么呢?我一定是从根本上误解了 'export' 在 shell

中的作用

我不知道这是否重要,但我正在使用 zsh

如果您在 shell 脚本中定义环境变量并将其导出,则在同一 shell 脚本中启动的 Python 程序将能够看到导出的环境变量剧本。请考虑下面这两个骨架脚本。这是 setvar.sh:

#! /bin/bash

export B=10

./getvar.py

而这个是 getvar.py:

#! /usr/bin/env python3 

import os

print(os.environ["B"])

那你运行setvar.sh:

$ ./setvar.sh 
10

至少在 bash 下,输出符合预期。即:getvar.py继承了setvar.sh.

定义的环境