0

I have a python program that periodically does some jobs according to that value of a given global variable "a". How can another python program change the value of "a" to (let's say) 20?

a = 10
def run_program():
    global a
    while True:
        time.sleep(1)
        print(a)

I tried with OS signals, but a signal (e.g. USR1) can't pass variables

Any helps?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Leo
  • 75
  • 1
  • 5
  • You can use an environment variable modify it in the first program and read it in the second one. – Mohamed Ali JAMAOUI May 15 '19 at 10:51
  • 1
    You taggerd [tag:interprocess] but your code does not show any attempt. Did you try anything from [https://docs.python.org/3.7/library/ipc.html](https://docs.python.org/3.7/library/ipc.html) ? If so , share it. Asking us to code for you is out of scope (too broad, offtopic) of this sites purpose. – Patrick Artner May 15 '19 at 10:55

1 Answers1

1

You can use an environment variable, modify it in the first program and use it the second one:

Program one:

import os
# Set environment variables
os.environ['YOUR_VARIABLE'] = 10

Program two:

import os
def run_program():
    a = os.environ.get('YOUR_VARIABLE')
    while True:
        time.sleep(1)
        print(a)

Notice also, that using this idea you avoid using a global variable.

Mohamed Ali JAMAOUI
  • 14,275
  • 14
  • 73
  • 117
  • I suppose that os.environ.get() is read inside the loop :-) Doing this, the variable is not affected by "Program one" :-/ – Leo May 15 '19 at 11:07
  • @Leo I don't understand the problem, you want to read the variable inside the loop ? , you can do that. – Mohamed Ali JAMAOUI May 15 '19 at 11:14