munich
munich

Reputation: 530

Can't make execfile() variables be global instead of local

I have this function:

#This function loads the tokens for the specified account. If the tokens are not found, it quits the script.
def selectAccountTokens():

global OAUTH_TOKEN
global OAUTH_SECRET
global CONSUMER_KEY
global CONSUMER_SECRET

if args.account == 'acc1':
    execfile('tokens/acc1.py')
    print "Account tokens were successfully loaded."

elif args.account == 'acc2':
    execfile('tokens/acc2.py')
    print "Account tokens were successfully loaded."

elif args.account == 'acc3':
    execfile('tokens/acc3.py')
    print "Account tokens were successfully loaded."

elif args.account == 'acc4':
    execfile('tokens/acc4.py')
    print "Account tokens were successfully loaded."

else:
    print "Account tokens were not found, or the argument is invalid."
    quit()

When I run it without making the variables OAUTH_TOKEN, OAUTH_SECRET, CONSUMER_KEY, CONSUMER_SECRET global, it fails.

I then made them global variables, but still when I run print OAUTH_TOKEN, it returns nothing.

I know I shouldn't be using global variables, but I can't figure a way to do it without global variables. Even though, the function is not populating the variables.

The contents of tokens/acc1.py is:

OAUTH_TOKEN = "gaergbaerygh345heb5rstdhb"
OAUTH_SECRET = "gm8934hg9ehrsndz9upnv09w5eng9utrh"
CONSUMER_KEY = "mdfiobnf9xdunb9438gj28-3qjejgrseg"
CONSUMER_SECRET = "esgmiofdpnpirenag8934qn-ewafwefdvzsvdfbf"

Upvotes: 1

Views: 596

Answers (1)

falsetru
falsetru

Reputation: 368944

global statement does not affect the environment the execfile execute.

Explicitly passing globals() will solve your problem:

execfile('tokens/acc1.py', globals())

BTW, the if .. elif ... elif .. can be reduced if you use string formatting operator % or str.format:

if args in ('acc1', 'acc2', 'acc3', 'acc4'):
    execfile('tokens/%s.py' % args)
    print "Account tokens were successfully loaded."
else:
    print "Account tokens were not found, or the argument is invalid."
    quit()

Upvotes: 2

Related Questions