0

I would like to set a couple of environment variables in a Python script, then use said environment variables in a chained call.

For example, a python script called set_env.py:

os.environ["MY_VAR"] = "cool value"

And then in bash

python ./set_env.py && echo "$MY_VAR"

Is such a thing possible?

I've tried to use the os.environ, os.system using export MY_VAR=..., but none of them seem to work.

3
  • This is in general not possible: unix.stackexchange.com/questions/30189/…. You can get the Python script to execute the other commands instead.
    – muru
    Commented Aug 28, 2024 at 8:23
  • 1
    What muru said. But can you explain why you want this? I mean, if you are setting shell variables, why do you even want to do it with a script in a different language? Why not use a shell script that you can source?
    – terdon
    Commented Aug 28, 2024 at 9:09
  • You can do it with export MY_VAR="cool value" for any shell environment also.
    – maxemilian
    Commented Aug 28, 2024 at 9:12

1 Answer 1

0

Since python runs in a child process of the shell it can't directly alter the shell's environment variables. However, your python script can output proper shell commands that can be evaluated in the shell.

$ python ./set_env.py
MY_VAR="x y z";MY_VAR2="a b c"

Then use the output of your python script like this:

$ eval "$(python ./set_env.py)" && echo "$MY_VAR"
x y z

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.