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

Time:03-06

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:

#!/bin/sh

#choose path to home
directory=~/.some_file

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

#I then export the variable
export directory

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

#!/usr/bin/env python3

import os

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

When I run the python file I get an error

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'

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

CodePudding user response:

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:

#! /bin/bash

export B=10

./getvar.py

And this one is getvar.py:

#! /usr/bin/env python3 

import os

print(os.environ["B"])

Then you run setvar.sh:

$ ./setvar.sh 
10

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

  • Related