pythonlinuxbashshellsh

how to make sub-shell env variable available in the main shell python console?


I open a python console and run

>>> import os
>>> os.system("export aaa=123")
>>> os.environ["aaa"]

I see a key error. Why is that? How can I preserve the env variables across the entire process?

note that this is not the right answer:

>>> import os
>>> os.environ['abc'] = '123'
>>> os.system('echo $abc')
123

the purpose of this question is to demonstrate a situation that a sub-shell is generating an env variable and one might want to share it with the parent shell


Solution

  • In general, a child shell cannot directly share or modify environment variables in the parent shell. When a child process is created, it receives a copy of the parent’s environment variables, but any changes made in the child process do not affect the parent process.

    Have you considered why you would like to do this? I would not like it if my child processes could modify my environment variables... this is a "code smell" issue.

    Consider, if you need to pass values between different sub-processes within a python script, using the multiprocessing module and in particular the multiprocessing.Queue class

    This provides a pythonic way to pass data between running python processes, that alleviates many of the headaches of rolling your own message queue, or even having to install/use a enterprise grade tool like Kafka.

    If that's not to your liking, then I'd recommend that you have a file that you maintain on the file system that contains the magic values that you need to pass between processes.

    The tl;dr; here is: If you can pull it off, it's still probably not the right thing to do.