NameError:未定义名称'filename'

时间:2017-11-29 23:44:02

标签: python filenames praw

我正在尝试关注reddit u / busterroni的video如何制作一个reddit机器人,但是当他的程序运行良好时,我一直挂在下面一行的“文件名”上说...

usernames = get_usernames(filename)

...在main()下。谁能告诉我这是什么问题?顺便说一句,我在视频中的时间是12:11,以防有任何帮助。

import praw
import sys


def main():
    reddit = authenticate()
    usernames = get_usernames(filename) #ERROR
    print(usernames)


def authenticate():
    print('Authenticating...')

    reddit = praw.Reddit(
        'notifier',
        user_agent="BlueWizard3's joketest v0.1")

    print('Authenticated as {}'.format(reddit.user.me()))

    return reddit


def get_usernames(filename):
    try:
        with open(filename, 'r') as f:
            usernames = f.read()
            usernames = usernames.split('\n')
            usernames = filter(None, usernames)
    except IOError:
        print('Error: file ', filename, " not found in the current directory.")
         quit()

    return usernames


main()


def send_message(r, username, subject, body):
    try:
        r.redditor(username).message(subject, body)
    except praw.exceptions.APIException as e:
        if 'USER_DOESNT_EXIST' in e.args[0]:
            print(e.args[0])

if len(sys.argv) != 4:
    print('usage: notifier.py file "subject" "body"')

filename = sys.argv[1] # ADDED
subject = sys.argv[2] # ADDED
body = sys.argv[3] # ADDED

for username in usernames:
    send_message(r, username, subject, body)

首次发布Stack Overflow,请耐心等待。

1 个答案:

答案 0 :(得分:1)

您的代码缺少为变量赋值的部分'文件名' 来自引用视频的code

这是在结束代码的第47行完成的,第37行是在11m左右:

47:    filename = sys.argv[1]
48:    subject = sys.argv[2]
49:    body = sys.argv[3]
50:
51:    r = bot_login()
52:    usernames = get_usernames(filename)

编辑:现在我们已经解决了这个问题,我们需要解决下一个问题,即你在main中获得的东西应该是在通过sys.argv传递值后才能直接使用。这意味着下面的代码不应该在' main'程序早期的方法,但在第50行之后

reddit = authenticate()
usernames = get_usernames(filename) #ERROR
print(usernames)