1

So, let's say that I got a shell script that generates a v.py on the output that contains

v = some-float

And I'm accessing it in the main.py script via from v import v But later the main Script toggles generation process again and the variable in v.py gets updated, but the variable v is not updating for the main script.

To make main script work I need to update the variable from v.py while script is running

I've tried importlib.reload(v) - didn't work

I'm still new to python and don't understand it completely

2
  • You might want to lookup on how to read from and write to text file in Python Commented Dec 7, 2018 at 6:41
  • 1
    You could rely on v.v instead of v. In this case, importlib.reload allows for the value of v.v to change. Commented Dec 7, 2018 at 6:45

1 Answer 1

1

Presuming you are using python 3.*, v needs to be a module, so the way you import it changes to example below.

import v
import importlib

print(v.v)

with open('v.py', 'w') as f:
    f.write('v = 20.0')

importlib.reload(v)
print(v.v)

Also note the document of importlib

"When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem."

Though our minimal example works, this is something to bear in mind for more complicated cases.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.