gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:59:09 24 4
gpt4 key购买 nike

我有这个功能:

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com