python - 无法使 execfile() 变量成为全局变量而不是局部变量

标签 python

我有这个功能:

#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"

最佳答案

global 语句不影响环境execfile执行。

显式传递globals()将解决您的问题:

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

顺便说一句,如果您使用 string formatting operator % ,则可以减少 if .. elif ... elif ..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()

关于python - 无法使 execfile() 变量成为全局变量而不是局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26695303/

相关文章:

python - Windows 上的 Pypy 和 Pillow?

python - os.times 返回值的第 5 位到底是什么意思?

python - 在 python 列表中查找下一个可用数字

python - PIL粘贴图像不模糊

python - 在 ubuntu 14.04 上安装 graph-tool 时配置错误

python - 如何在 PyOpenGL 中使用 glBufferData()?

python - 如何在 OpenShift 上使用 mongohq 或 mongolab

python - 模块未找到错误 : No module named 'psycopg2' (But it is installed)

python - 导入模块时出错 - 配置不正确 : WSGI application

python - pyodbc连接字符串sql server身份验证