通过批处理文件运行Python脚本时无法找到已安装库的问题求助
Problem Overview
When running a Python script via a batch file, you’re encountering a ModuleNotFoundError (specifically for the requests library, as shown in the error screenshot):
Your batch file uses a direct path to the Python 3.10 executable:
@echo off "C:\Users\juliu\AppData\Local\Programs\Python\Python310\python.exe" "C:\Users\juliu\Desktop\Evolo project\Website_scraper_system_2\blocket_scraper.py" pause
Root Cause Explanation
The error happens because the Python interpreter specified in your batch file doesn’t have the required libraries installed in its associated site-packages directory. Here’s the breakdown:
Mismatched interpreter and package installation: When you install packages with
pip, they’re tied to the specific Python interpreter that runspip. If you installedrequestsusing a different Python version (e.g., a system-wide install, another Python instance) or apipnot linked to your Python 3.10 folder, the package won’t be visible to the interpreter in your batch file.Incorrect pip usage: If you ran
pip install requestswithout specifying the pip executable from your Python 3.10 installation, the package was likely installed to a different Python’ssite-packagesinstead of the one your batch file uses.Virtual environment isolation: If your project uses a virtual environment, the batch file isn’t activating it. Packages installed in a venv are only available when the environment is active, so the global Python 3.10 interpreter won’t detect them.
Fixes to Resolve the Issue
Install packages for the target interpreter: Run this command in Command Prompt to install
requestsspecifically for the Python 3.10 instance in your batch file:C:\Users\juliu\AppData\Local\Programs\Python\Python310\Scripts\pip.exe install requestsActivate virtual environment (if using one): Modify your batch file to activate the venv before running the script. For example, if your venv is in the project folder:
@echo off cd "C:\Users\juliu\Desktop\Evolo project\Website_scraper_system_2" call venv\Scripts\activate.bat python blocket_scraper.py pauseVerify package installation: Confirm the package is installed correctly for the target interpreter by running:
C:\Users\juliu\AppData\Local\Programs\Python\Python310\python.exe -c "import requests; print(requests.__version__)"If this outputs the package version, it’s properly installed for that interpreter.
内容的提问来源于stack exchange,提问作者Julius Olsson

