python - Execfile running the file twice when used with import -
i want have textbox , button in gui , on clicking button, should take text , store in variable other file , run other file.
i want user enter access token , gui should save in global variable access_token of utilities.py when importing function setting access token only, file runs don't want until button clicked. so, file running twice.
this gui.py
from tkinter import * import tkinter tk utilities import setaccesstoken root = tk.tk() def callback(): setaccesstoken(e1.get()) execfile('utilities.py') e1 = entry(root,bd = 5, width = 10) e1.pack() #similarly other gui stuff command = callback() mainloop()
this utilities.py
access_token = "" def setaccesstoken(token): global access_token access_token = token print 'running utilities : access_token =', access_token
my expected output is:
running utilities: access_token = access token
but getting output twice, is:
running utilities: access_token = running utilities: access_token = access token
is there way in can stop file utilities.py running when importing it?
when import python file, code in executed. that's how python works. prevent executing unwanted code, should use __name__
this:
access_token = "" def setaccesstoken(token): global access_token access_token = token if __name__ == '__main__': print 'running utilities : access_token =', access_token
Comments
Post a Comment