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

  Kiến thức lập trình

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?

os.system() creates a subshell. Subshells do not have access to their parent environment (it’s copied). They can not modify it. You could change your current environment (not a child one) and have the subshells inherit it:

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

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.

Set the environment variable in the Python process

os.environ['aaa'] = "123"

Now, or later in the process you can access it as a normal environment variable

print(os.environ['aaa'])

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT