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

dftag
  • 85
  • 2
  • 8
  • 3
    How did you execute the shell script? Unless it runs the Python script for you, you have to *source* the shell script so that the export takes place in the shell from which Python is started. – chepner Mar 04 '22 at 16:08
  • 2
    See also: [Can I export a variable to the environment from a Bash script without sourcing it?](https://stackoverflow.com/questions/16618071/can-i-export-a-variable-to-the-environment-from-a-bash-script-without-sourcing-i) – Mark Mar 04 '22 at 16:12

1 Answers1

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.

Hilton Fernandes
  • 559
  • 6
  • 11