使用PyInstaller打包PRAW Python脚本为exe时出现AttributeError错误
This error occurs because your packaged EXE can't access the PRAW configuration values it expects, leading to placeholder _NotSet values that break when PRAW tries to process them (like calling .lower() on a boolean config option). Here are the most reliable fixes:
Root Cause
By default, PRAW reads configuration from a praw.ini file. When you package your script with PyInstaller, this file isn't automatically included in the EXE bundle. Without it, PRAW uses uninitialized _NotSet values instead of valid configuration strings/booleans.
Solution 1: Include praw.ini in the EXE Bundle
Step 1: Package with PyInstaller and Add the Config File
Use the --add-data flag to include your praw.ini file in the bundle:
pyinstaller --add-data "praw.ini;." background.py
(On macOS/Linux, replace ; with :: --add-data "praw.ini:.")
Step 2: Update Your Script to Find the Config File
PyInstaller extracts bundled files to a temporary directory at runtime. Add this helper function to your script to locate praw.ini correctly:
import sys import os def resource_path(relative_path): """Get absolute path to resource, works for development and PyInstaller""" try: base_path = sys._MEIPASS # PyInstaller's temp directory except Exception: base_path = os.path.abspath(".") # Default to current directory return os.path.join(base_path, relative_path)
Then initialize PRAW with the resolved config path:
import praw reddit = praw.Reddit( config_file=resource_path("praw.ini"), config_section="your_config_section_name" # Optional: specify section if using multiple )
Solution 2: Hardcode Configuration Values (Simplest for Single-Use Apps)
Avoid relying on praw.ini entirely by passing all required parameters directly when initializing PRAW:
import praw reddit = praw.Reddit( client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", user_agent="YOUR_USER_AGENT_STRING", # Add other parameters like username/password if needed for your use case )
This eliminates any dependency on external config files and works seamlessly with PyInstaller.
Solution 3: Use Environment Variables
PRAW can read configuration values from environment variables. You can set these before running the EXE, or define them in your script:
import os import praw # Set environment variables (optional: can also set them outside the script) os.environ["PRAW_CLIENT_ID"] = "YOUR_CLIENT_ID" os.environ["PRAW_CLIENT_SECRET"] = "YOUR_CLIENT_SECRET" os.environ["PRAW_USER_AGENT"] = "YOUR_USER_AGENT_STRING" reddit = praw.Reddit() # PRAW automatically reads from env vars
Content of the question来源于stack exchange,提问作者Recessive

