You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PRAW初始化后遭遇NameError:reddit变量未定义的问题求助

PRAW初始化后遭遇NameError:reddit变量未定义的问题求助

看起来你遇到的问题特别典型——明明按照PRAW文档写了初始化代码,结果Python却告诉你reddit变量没定义。别着急,咱们一步步拆解问题根源和解决办法:

核心原因分析

你代码里的reddit = praw.Reddit(...)这条赋值语句,如果在执行过程中抛出了异常(比如API凭证错误、网络问题、PRAW版本不兼容等),那么这个变量就不会被成功创建。而你现在的代码没有对这段初始化逻辑做异常捕获,所以程序会在初始化失败时直接中断,但你可能没注意到前面的错误输出,只看到了后面的NameError。

具体排查和解决步骤

1. 给Reddit初始化加上异常捕获,暴露真实错误

先把初始化代码改成带异常处理的版本,这样能直接看到初始化时的具体问题:

try:
    # Initialize Reddit API credentials
    reddit = praw.Reddit(
        client_id="redacted",
        client_secret="redacted",
        password="redacted",
        user_agent="redacted",
        username="redacted",
    )
    print(reddit.read_only) #test
except Exception as e:
    print(f"初始化Reddit API时出错了: {str(e)}")
    logging.error(f"初始化Reddit API失败: {str(e)}")
    raise  # 终止程序,先解决初始化问题

运行后如果初始化有问题,你会看到具体错误,比如凭证无效、user_agent格式不符合要求等。

2. 逐一核对你的Reddit API凭证

这是最常见的坑,一定要仔细检查:

  • client_id & client_secret:去Reddit的应用管理页面确认,你创建的是「personal use script」类型的应用,client_id是应用名称下方的一串随机字符(不是应用名),client_secret是页面上「secret」字段的值。
  • user_agent:必须符合格式要求,比如"stock-mention-tracker-v1 by u/你的Reddit用户名",不能用太通用的描述,Reddit会拒绝这种请求。
  • 用户名和密码:确认是你Reddit账号的正确登录信息,注意大小写和特殊字符有没有输错。

3. 检查你的conda环境和PRAW版本

  • 确认VSCode正在使用你配置的conda环境:点击VSCode右下角的Python解释器选择器,切换到你的目标conda环境(比如base或者你新建的环境),避免出现“环境里没装PRAW”的情况。
  • 升级PRAW到最新版本:在conda环境的终端里执行pip install --upgrade praw,旧版本可能存在一些兼容性问题。

4. 额外小提醒(解决当前问题后)

看你的代码,在处理评论的时候有个小bug:

for symbol in stock_symbols:
    if re.search(r'\b' + re.escape(symbol) + r'\b', text_to_search, re.IGNORECASE):
        all_mentions.append(symbol)
# ...
for comment in submission.comments.list():
    if hasattr(comment, 'body'):
        if re.search(r'\b' + re.escape(symbol) + r'\b', comment.body, re.IGNORECASE):
            all_mentions.append(symbol)

这里的symbol是外层循环的最后一个值,也就是说评论只会检查最后一个股票符号,不是所有符号。你需要把评论的循环放到for symbol in stock_symbols里面,或者换一种方式匹配所有股票符号,不过这是后话,先解决当前的初始化问题~


你的原始问题信息

问题描述

Very much a noob question. I'm trying to code with copilot and some (many) things in the code need fixing. However I can't progress past this error. I've installed and imported praw, I've defined the variable following the praw documentation format, but python is still telling me I haven't defined it? I'm running the python extenstion in VScode in a conda environment (I think that's what I set up).
Also yes, I did create an app in reddit so I'd get the IDs

For this specific problem, I'm just expecting to be authenticated into reddit. I'll then use this to pull certain information from other subreddits. The reddit variable should be clearly defined above, but python doesn't recognize it.

原始代码

import praw
import datetime
import pandas as pd
from collections import Counter
import os
import logging
import re
import alpaca_trade_api as tradeapi

# Configure logging
logging.basicConfig(filename='stock_report.log', level=logging.INFO, 
                    format='%(asctime)s - %(levelname)s - %(message)s')

# Initialize Reddit API credentials
reddit = praw.Reddit(
    client_id="redacted",
    client_secret="redacted",
    password="redacted",
    user_agent="redacted",
    username="redacted",
)

print(reddit.read_only) #test

# Subreddits to search
subreddits = ["stocks", "wallstreetbets", "wallstreetbetsELITE", "valueinvesting", "pennystocks"]

# Timeframe for analysis (e.g., last 24 hours)
time_delta = datetime.timedelta(days=300)
end_time = datetime.datetime.now(datetime.timezone.utc)
start_time = end_time - time_delta
logging.info(f"Analyzing posts from {start_time} to {end_time}")

# Get all available stock symbols from Alpaca
try:
    api = tradeapi.REST('redacted', base_url='https://paper-api.alpaca.markets')
    assets = api.list_assets(status='active')
    stock_symbols = [asset.symbol for asset in assets if asset.exchange == 'NASDAQ' or asset.exchange == 'NYSE']
    logging.info(f"Loaded {len(stock_symbols)} stock symbols from Alpaca.")
except Exception as e:
    logging.error(f"Error loading stock symbols from Alpaca: {e}")
    raise

all_mentions = []

for subreddit_name in subreddits:
    try:
        subreddit = reddit.subreddit(subreddit_name)
        logging.info(f"Processing subreddit: {subreddit_name}")
        submission_count = 0
        for submission in subreddit.new(limit=500):
            submission_time = datetime.datetime.fromtimestamp(submission.created_utc, datetime.timezone.utc)
            if start_time <= submission_time <= end_time:
                submission_count += 1
                text_to_search = (submission.selftext or "") + " " + submission.title
                logging.info(f"Searching text: {text_to_search}")
                for symbol in stock_symbols:
                    if re.search(r'\b' + re.escape(symbol) + r'\b', text_to_search, re.IGNORECASE):  # Word boundary regex
                        all_mentions.append(symbol)
                submission.comments.replace_more(limit=0)
                for comment in submission.comments.list():
                    if hasattr(comment, 'body'):
                        if re.search(r'\b' + re.escape(symbol) + r'\b', comment.body, re.IGNORECASE): # Word boundary regex
                            all_mentions.append(symbol)
        logging.info(f"Retrieved {submission_count} submissions from {subreddit_name} within the time range.")
    except praw.exceptions.APIException as e:
        logging.error(f"PRAW API Error in {subreddit_name}: {e}")
    except Exception as e:
        logging.error(f"Error processing subreddit {subreddit_name}: {e}")

# Count mentions
mention_counts = Counter(all_mentions)
print(all_mentions)

# Create a Pandas DataFrame for the report
report_data = {'Stock Symbol': list(mention_counts.keys()),
               'Mentions': list(mention_counts.values())}
df_report = pd.DataFrame(report_data)

if not df_report.empty:
    df_report = df_report.sort_values(by='Mentions', ascending=False)
    print(df_report)
    df_report.to_csv("stock_report.csv", index=False)
    logging.info("Report saved to stock_report.csv")
    print("Report saved to stock_report.csv")
else:
    print("No stock mentions found in the specified time range.")
    logging.info("No stock mentions found in the specified time range.")

错误信息

Traceback (most recent call last):
  File "c:\Users\fdossantos\Code\Untitled-2.py", line 26, in <module>
    print(reddit.read_only)
          ^^^^^^
NameError: name 'reddit' is not defined

备注:内容来源于stack exchange,提问作者Francisco Dos Santos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 16:59:31