我在代码中放置了global user
以查看它是否在某个地方丢失了,但似乎没有。基本上,当我在这里看到的这段代码中分配了全局变量user
之后调用userInstance.getName()
:
if(userName in nameList):
for userdata in pklList:
if userdata.getName() == userName:
global user
user = userdata
print("user data found for user: " + user.getName())
它看起来并没有真正进入全局变量。以下是目前代码的完整版本:
import praw
import time
import re
import pickle
from classes import User
USERAGENT = 'web:CredibilityBot:v0.1 (by /u/ThePeskyWabbit)'
FOOTER = "^^I ^^am ^^a ^^bot! ^^I ^^am ^^currently ^^in ^^test ^^phase. ^^Read ^^about ^^me ^^[here](https://pastebin.com/jb4kBTcS)."
PATH = "C:\\Users\\JoshLaptop\\PycharmProjects\\practice\\commented.txt"
user = User.User("ERROR")
commentFile = open(PATH, 'rb')
commentList = commentFile.read().splitlines()
commentFile.close()
pkl = open("userpkl.pkl", 'rb')
pklList = []
print(pklList)
try:
pickle.load(pkl)
while(True):
pklList.append(pickle.load(pkl))
except EOFError:
pass
pkl.close()
nameList = []
try:
for data in pklList:
nameList.append(str(data.getName()))
except:
pass
print(pklList)
print(nameList)
def addPoint(comment):
message = "current name for user: " + user.getName()
#userInstance.addScore()
#userInstance.addComment(comment)
#message = "Bullshit noted! " + userInstance.getName() + " now has a Bullshit rating of " + userInstance.getScore() + "\n\n" + FOOTER
return message
def getRating():
message = user.getName() + " has a Bullshit rating of: " + user.getScore()
return message
def getCommentList():
bullshitComments = user.getComments()
return bullshitComments
auth = True
def authenticate():
print("Authenticating...")
reddit = praw.Reddit('bot1', user_agent=USERAGENT)
print("Authenticated as {}\n" .format(reddit.user.me()))
return reddit
commentLink = None
actions = {"!bullshit": addPoint(commentLink), "!bullshitrating": getRating(user), "!bullshitdetail":getCommentList(user)}
stringList = ["!bullshit", "!bullshitrating", "!bullshitdetail"]
while(auth):
try:
reddit = authenticate()
auth = False
except:
print("Authentication Failed, retying in 30 seconds.")
time.sleep(30)
def runBot():
SUBREDDITS = 'test'
global user
while(True):
print("Scraping 1000 comments...")
for comment in reddit.subreddit(SUBREDDITS).comments(limit=1000):
for word in stringList:
match = re.findall(word, comment.body.lower())
if match:
id = comment.id
commentFile = open(PATH, 'r')
commentList = commentFile.read().splitlines()
commentFile.close()
if(id not in commentList):
print(match[0] + " found in comment: " + "www.reddit.com" + str(comment.permalink()))
commentLink = "www.reddt.com" + str(comment.parent().permalink())
print("Bullshit comment is: " + commentLink)
print("searching for user data")
userName = str(comment.parent().author)
flag = True
if(userName in nameList):
for userdata in pklList:
if userdata.getName() == userName:
user = userdata
print("user data found for user: " + user.getName())
elif comment.parent().author is not None:
print("no user found, creating user " + userName)
user = User.User(userName)
f = open("userpkl.pkl", 'ab')
pickle.dump(user, f)
f.close()
nameList.append(userName)
print("added to user to pkl file")
else:
print("username could not be retrieved.")
print("adding ID to log\n")
commentFile = open(PATH, 'a')
commentFile.write(id + "\n")
commentFile.close()
flag = False
if(flag):
try:
print(actions[match[0]])
#print("sending reply...")
#comment.reply(actions[match[0]])
#print("Reply successful. Adding comment ID to log\n")
#commentFile = open(PATH, 'a')
#commentFile.write(id + "\n")
#commentFile.close()
except:
print("Comment reply failed!\n")
runBot()
奇怪的是,当我在指定的代码片段中调用user.getName()
时,它会输出正确的名称,而不是像我在addPoint()
函数中调用它时那样输出“error”
打印语句输出如下:
C:\Python36-32\python.exe C:/Users/JoshLaptop/PycharmProjects/practice/TestBot.py
[]
[<classes.User.User object at 0x03B59830>, <classes.User.User object at 0x03816430>]
['PyschoWolf', 'ThePeskyWabbit']
Authenticating...
Authenticated as CredibilityBot
Scraping 1000 comments...
!bullshit found in comment: link deleted for privacy
Bullshit comment is: link deleted for privacy
searching for user data
user data found for user: PyschoWolf
current name for user: ERROR
!bullshit found in comment: link deleted for privacy
Bullshit comment is: link deleted for privacy
searching for user data
user data found for user: ThePeskyWabbit
current name for user: ERROR
在python中,如果您的代码对一个变量进行赋值,那么除非显式声明,否则该变量被假定为局部变量。如果您显式地声明它们,则它们是全局的
然而,Globals是“每个模块”
通常不清楚的是,当您导入一个名称时,会发生这样的情况:导入的值的一个副本在当前模块中作为一个具有相同名称(或者如果同时使用
as
,则为另一个名称)的模块全局生成。例如:请注意,Python中有一些关于这一点的“魔力”,函数会记住它们是在哪个模块中定义的。假设我有:
(1)发生的原因是
user
只是程序的全局,而不是模块的全局。值是在导入时从模块复制到程序的,仅此而已(2)原因相同。在模块中编译的代码将被视为该模块的全局变量,而不是程序。尽管调用是在程序中进行的,并且
getUser
变量(包含函数)在这里,但仍会发生这种情况。它的功能是“记住”它应该访问哪些全局变量代码
与相同
相对于整个程序,Python没有真正的“globals”。像
x = 3
这样的语句总是修改局部变量、捕获的变量(nonlocal
声明)或全局模块。“真正的全局”根本不存在(如果您真的需要它们,您可以做的是为全局创建一个特定的模块,并用myglobs.var
而不是var
引用它们)附言:密码
看起来很奇怪。参数
userInstance
被覆盖。也许你的意思是相反呢
相关问题 更多 >
编程相关推荐