1

I know that os.getenv and os.environ will allow me to read the values of environment variables as of os package import, but I'm writing a program that needs to detect the size of the terminal window dynamically. It would be great to do this without starting a subprocess each time. I am also aware of other solutions (that page also gives the sub-process solution), but I am curious about whether there is a direct solution to this simple-seeming problem of getting the current value of an environment variable.

Community
  • 1
  • 1
Nat Kuhn
  • 9,493
  • 5
  • 18
  • 26
  • The problem is that the python process gets a _copy_ of the environment at startup. Bash (or whatever shell you are using) actively monitors the terminal size, and changes its environment accordingly -- but python does not do that. Changes to the environment in the shell do not pass through to subprocesses after they have started. – Markku K. Jan 29 '15 at 16:53
  • Thanks, @MarkkuK. It seems like you are saying that this is something that is impossible in *nix, not just in Python, is that correct? – Nat Kuhn Jan 30 '15 at 02:17
  • That's correct - processes do not have access to the environments of other running processes, regardless of parent/child relationships. – Markku K. Jan 30 '15 at 03:13
  • @MarkkuK.: thanks, this is the answer to my question, i.e. this is impossible in Python or any other programming language; a process only has access to the parent process's environment variables at the moment of its birth. If you would like to post that as an answer I will happily accept it! – Nat Kuhn Jan 30 '15 at 22:34

2 Answers2

1

In general, the answer is that it is not possible to get the current value of an environment variable in one process from another process (unless you explicitly add a way of communicating this info). When one process forks another process, it can specify the startup environment of the child process, but that is as far as it goes. The child process does not see any changes in the environment made by its parent.

Markku K.
  • 3,840
  • 19
  • 20
0

As the alluded to post mentions, there is a solution using just the os library. That's about as canonical as you can get.

Dylan Lawrence
  • 1,503
  • 10
  • 32