1

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?

ronilp
  • 455
  • 2
  • 9
  • 25
  • why not wrap print 'Running Utilities : access_token =', access_token logic in a function and invoke that instead of execfile.This way you can also avoid the print during import – keety Apr 25 '15 at 04:11
  • May I ask what's the purpose of `execfile`? – number5 Apr 25 '15 at 04:13
  • There are some other buttons as well which should run some other files. That is why I need to use execfile. – ronilp Apr 25 '15 at 04:19
  • Wrapping the code written in the files will be time consuming because I have a lot of files. – ronilp Apr 25 '15 at 04:21

1 Answers1

2

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
ljk321
  • 16,242
  • 7
  • 48
  • 60