So there’s two scripts: script1.py
and script2.py
. script1.py
has a variable x
that stores the string read from a file during runtime. In script2.py
, I import script1.py
and then run script1.py
using the following: script1.main()
. I then run a particular function in script1.py
that is responsible for reading the file in question.
You might wonder why I don’t just run that particular function in the first place instead of running the whole script. That’s because script1.py
does a bunch of other things that script2.py
needs every time it is run.
I want to able to read what is stored in x
when script1.py
is run from script2.py
. What I’m currently doing is essentially running part of script1.py
twice. I want to know if it’s possible to access the variable x
without doing the following:
#script1 def read_file(): f = open('file_path.txt') string = f.read() return string def main(): x = read_file() if __name__ == '__main__': main()
And script2.py
:
#script2 import script1 from script1 import * def main(): script1.main() x = read_file() print(x) if __name__ == '__main__': main()
So essentially I want to know how this sort of thing is supposed to be done usually. Is it possible to get the value of x
without having to run read_file()
a second time? When script1.main()
is executed, where is the value of x
stored and how can I access it? Not sure if I should be using import script1
or if I should use from script1 import *
to achieve this.
Advertisement
Answer
Since x
is a local variable in the script1.main
function, it is not accessible from outside (neither from script2 nor even from script1). In fact, the object will be discarded after script1.main
is finished.
If you want to reuse it, you need to store it somewhere else.
A quick fix is to make the variable x
global. Then script2 can use it as script1.x
.
# script1.py def read_file(): return "foo bar" def main(): global x x = read_file() if __name__ == '__main__': main() # script2 import script1 def main(): script1.main() #x = read_file() print(script1.x) if __name__ == '__main__': main()
If you do not want to use the global
syntax, an alternative is to define a mutable variable in the script1.py
and let it store the variable you want to reuse. One possibility is to use class
. Here, I am using class
as a mutable storage. If you do not like it, other mutable objects such as dict
would also work.
# script1.py class data: x = None def read_file(): return "foo bar" def main(): data.x = read_file() if __name__ == '__main__': main() # script2 import script1 def main(): script1.main() #x = read_file() print(script1.data.x) if __name__ == '__main__': main()