2017-08-26 59 views
1

我已經做了我的公平份額玩弄global user在代碼中的位置,以查看它是否在某處丟失,但它似乎並不是。基本上當我呼籲userInstance.getName()在此塊的代碼在這裏看到分配全局變量user後:全局變量沒有被功能編輯

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() 

和什麼奇怪的是,當我的代碼afformentioned的這段中調用user.getName(),它輸出的正確名稱,而不是「錯誤」,因爲它確實當我打電話它在我的addPoint()函數中。

報表打印輸出如下:

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 
+0

哪裏是「錯誤」是從哪裏來的?在輸出「錯誤」的代碼中,我看不到任何地方。如果您收到錯誤消息,請將其顯示出來。你確定在使用之前初始化'user'?嘗試在程序頂部附近的外部代碼中初始化它。 – cdarke

+0

從'user.getName()' 作爲分配的代碼的頂部線條的默認名稱爲「ERROR」 – ThePeskyWabbit

+0

[當詢問關於由您的代碼中的問題的問題,你會得到更好的答案,如果你提供代碼的人可以用它來重現問題。(https://stackoverflow.com/help/mcve) – gboffi

回答

0

在Python中,如果你的代碼進行分配給一個變量的話,除非明確說明,該變量被認爲是本地。如果你明確地聲明他們,他們是全球性的。

然而全局是「每個模塊」。

東西往往是不明確的是,當你輸入一個名稱會發生​​什麼情況是,進口的副本在當前模塊作爲全球使用相同的名稱(或者不同名稱的模塊中,如果使用發。也as例如:

from xxx import user 
# xxx.user has been copied to a globl named user 

user = "baz" # <--- this DOES NOT change xxx.user 

xxx.user = "ohyeah" # Now it changes xxx.user 

注意,在Python這個東西「神奇」,但它是功能會記住哪個模塊定義它們假設我有:

# module.py 

user = "No user yet" 

def setUser(newUser): 
    global user 
    user = newUser 

def getUser(): 
    return user 

# program.py 
from module import user, setUser, getUser 

print(user)  # --> "No user yet" 
print(getUser()) # --> "No user yet" 

setUser("Hey") 

print(user)  # --> "No user yet" (1) 
print(getUser()) # --> "Hey" 

user = "Foo" 
print(user)  # --> "Foo" 
print(getUser()) # --> "Hey" (2) 

(1)發生,因爲user只是程序的全局,而不是模塊的全局。該值在導入時從模塊複製到程序,並且全部都是

(2)發生的原因相同。在模塊中編譯的代碼將看作是全局模塊,而不是程序。儘管調用是在程序中進行的,並且getUser變量(包含函數)在這裏,但是會發生這種情況。這是「記住」它應該訪問的全局變量的函數。

代碼

from xxx import yyy 

相同

import xxx 
yyy = xxx.yyy # simple assignment to a global 

Python有沒有真正的 「全局」 相對完整的程序。像x = 3這樣的語句將總是修改局部變量,捕獲的變量(nonlocal聲明)或全局模塊。一個「真正的全球化」根本不存在(如果你真的需要它們,你可以做的是創建一個特定的全局模塊和引用myglobs.var而不是var)。

PS:代碼

def addPoint(userInstance, comment): 
    global user 
    userInstance = user 
    message = "current name for user: " + userInstance.getName() 

看起來很奇怪。參數userInstance被覆蓋。可能是你的意思

user = userInstance 

取而代之?

+0

我明白這一點,但在您的示例中,我試圖將「baz」更改爲「graz」,並將其保留爲「baz」。我將如何解決這個問題? – ThePeskyWabbit

+0

即 '用戶= object1'需要進行更改,以便用戶'= object2' – ThePeskyWabbit

+0

使用我剛試過'classes.user = userData'並沒有奏效。我也嘗試過'User.user = userData',它無法改變全局'用戶' – ThePeskyWabbit