pythonuser-interfacetkinterpython-importexecfile

Execfile running the file twice when used with import


I want to have a textbox and a button in my GUI and on clicking the button, it should take the text and store it in a variable for some other file and run the other file.

I want the user to enter an access token and the GUI should save it in the global variable access_token of utilities.py But when importing the function for setting the access token only, the file runs which I don't want until the button is clicked. So, effectively the file is running twice.

This is my gui.py

from Tkinter import *
import Tkinter as tk
from 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 with command = callback()

mainloop()

This is my 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 = my access token

But I am getting the output twice, that is:

Running Utilities: access_token =
Running Utilities: access_token = my access token

Is there any way in which I can stop the file utilities.py from running when I am importing it?


Solution

  • When you import a python file, all the code in it will be executed. That's how python works. To prevent executing unwanted code, we should always use __name__ like this:

    access_token = ""
    def setAccessToken(token):
        global access_token
        access_token = token
    
    if __name__ == '__main__':
        print 'Running Utilities : access_token =', access_token