1

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

asked Mar 4, 2022 at 16:05
2

1 Answer 1

2

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.

answered Mar 4, 2022 at 16:26
Sign up to request clarification or add additional context in comments.

2 Comments

It runs as expected using zsh as well. Thanks!
Thank you for presenting an interesting problem.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.