Emilio Garcia Emilio Garcia - 1 month ago 9
Python Question

Update variables in a loop in one python script with input from another python script

This is just an exercise to see how something like this would be done.

In file "variables.py" I have:

x=5
while True:
x=input('input x: ')


In file "loop.py" I have:

import time
from variables import x
while True:
print(str(x))
time.sleep(2)


My goal is to have both programs running, where variables.py constantly asks for a new x value, and loop.py automatically updates the value of x in its loop. I set x=5 so that there's an initial value before I input anything.

Instead, when I run loop.py, I'm given an input prompt. How can I go about achieving something like this?

Answer

I don't know if from variables import x works while you run variables.py. So I would suggest to save x in a file what is used by both scripts (but not at the same time!):

x = 5
while True:
    x = input('input x: ')
    f = open('x.txt', 'w')
    f.write(x)
    f.close()

and

import time
while True:
    f = open('x.txt', 'r')
    print(f.read())
    f.close()
    time.sleep(2)