2

Here's my script:

try:
    os.environ['CONSOLE'] = '1'
    while True:
        ...
except KeyboardInterrupt:
    del os.environ['CONSOLE']

I'm trying to set an environment variable called CONSOLE. While this program is running that variable should exist, once I exit out of it with Ctrl+C it should disappear.

When I leave the program running and try printing it from my shell, however, I get:

$ echo $CONSOLE
CONSOLE: Undefined variable.

I can't seem to read it from my PHP script either. Where's my variable? I thought os.environ should allow me to do this?

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • 3
    You cannot do this. The variables will not persist and won't be available in the parent shell. You need to pass the information in some other way. – Noufal Ibrahim Jan 08 '14 at 16:57
  • What's the easiest way to share a single boolean between a Python script and a PHP script then? Polling a file seems a bit lame. – mpen Jan 08 '14 at 16:59
  • 1
    `echo export CONSOLE=1 >> ~/.bash_rc` then `sh ~/.bash_rc` but I dont think thats quite what your looking for ... what are you actually trying to do? your best be may be to rethink your approach (this reminds me of those XY problems) – Joran Beasley Jan 08 '14 at 17:05
  • Depends on where they're running. If one launches the other, a command line argument or an environment variable will work. Otherwise, some form of IPC. – Noufal Ibrahim Jan 08 '14 at 18:42

1 Answers1

6

It's the nature of how a shell works, each new process is fork/exec'd, so your Python script is running in a separate process from the shell that started it.

Setting environment variables, through whatever means, won't change the variables in the shell it was started from because the script's environment and the original shell's environment are distinct.

As you can see here, it's not getting lost after the script, but even while python is still running (bash 4.2, python 3.3)

>>> import os
>>> os.environ['CONSOLE'] = '1'
>>> 
[1]+  Stopped                 python3.3
$ echo $CONSOLE

$ fg
python3.3

>>> os.environ['CONSOLE']
'1'

If you're trying to effectively get named shared memory between the PHP and Python scripts, you could use a FIFO and read/write to as you would a file, or communicate over a socket.

Community
  • 1
  • 1
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174