我有这个功能:
#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()
当我在不使变量OAUTH_TOKEN, OAUTH_SECRET, CONSUMER_KEY, CONSUMER_SECRET
全局的情况下运行它时,它会失败。
然后我将它们作为全局变量,但是当我运行print OAUTH_TOKEN
时,它仍然没有返回任何内容。
我知道我不应该使用全局变量,但如果没有全局变量,我无法想办法。即使这个函数没有填充变量。
tokens/acc1.py
的内容是:
OAUTH_TOKEN = "gaergbaerygh345heb5rstdhb"
OAUTH_SECRET = "gm8934hg9ehrsndz9upnv09w5eng9utrh"
CONSUMER_KEY = "mdfiobnf9xdunb9438gj28-3qjejgrseg"
CONSUMER_SECRET = "esgmiofdpnpirenag8934qn-ewafwefdvzsvdfbf"
答案 0 :(得分:2)
global
语句不会影响execfile
执行的环境。
明确传递globals()
将解决您的问题:
execfile('tokens/acc1.py', globals())
顺便说一句,如果您使用string formatting operator %
或str.format
,if .. elif ... elif ..
可以减少:
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()