Skip to content
Advertisement

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

This question has been asked before here, but when I try to emulate the correct answer I get a key error, and I’m wondering what I’m doing wrong.

I have a shell script that creates a directory in home:

JavaScript

Then I go over to my python script, and I want to use the variable directory from my shell script as the same variable in my python script

JavaScript

When I run the python file I get an error

JavaScript

So I’m assuming i’m getting a None returned for the variable from the error message, but why? I must be fundamentally misunderstanding what ‘export’ does in the shell

I don’t know if this matters, but I’m using zsh

Advertisement

Answer

If you define your environment variable in a shell script and exports it, a Python program started in the same shell script will be able to see the environment variable exported in the script. Please consider these two, skeletal scripts below. This is setvar.sh:

JavaScript

And this one is getvar.py:

JavaScript

Then you run setvar.sh:

JavaScript

At least under bash, the output is as expected. That is: getvar.py has inherited the environment defined by setvar.sh.

Advertisement