如何为每个Python脚本指定专属解释器(Windows 10环境)
Hey there! I get your frustration—dealing with interpreter mismatches when running scripts outside your IDE can be a real pain. Let's break down easy, practical ways to make each script use its own dedicated virtual environment without relying on PyCharm or cluttering your global interpreter.
1. Directly Call the Project's Virtual Environment Interpreter
Every PyCharm project's virtual environment has its own python.exe executable. Instead of using the system's default python command, you can run your script with this specific interpreter:
- First, locate your project's virtual environment path. For your
mcdisproject, it should be something likeC:\Users\Andrei\PycharmProjects\mcdis\venv\Scripts\python.exe - Open Command Prompt (CMD) or PowerShell, then run:
"C:\Users\Andrei\PycharmProjects\mcdis\venv\Scripts\python.exe" "C:\Users\Andrei\PycharmProjects\mcdis\mcdis.py"
This tells Windows exactly which interpreter to use, so it will find the discord library you installed in the project's venv.
2. Create a Batch File for One-Click Execution
If typing that long command every time is annoying, make a batch (.bat) file to automate it:
- Right-click in your project folder, select New > Text Document
- Rename it to
run_mcdis.bat(make sure file extensions are visible in Windows so you don't end up with.bat.txt) - Open the file in Notepad and paste this:
@echo off "C:\Users\Andrei\PycharmProjects\mcdis\venv\Scripts\python.exe" "C:\Users\Andrei\PycharmProjects\mcdis\mcdis.py" pause - Save it. Now you can just double-click this
.batfile to run your script with the correct interpreter—no command line typing needed!
3. Activate the Virtual Environment in Command Line
If you prefer using the command line occasionally, you can activate the project's virtual environment first, then run the script:
- Open CMD/PowerShell and navigate to your project folder:
cd C:\Users\Andrei\PycharmProjects\mcdis - Activate the virtual environment:
You'll seevenv\Scripts\activate.bat(venv)appear at the start of your command prompt—this means you're now using the project's interpreter. - Run your script normally:
python mcdis.py
When you're done, just type deactivate to exit the virtual environment.
Why This Happens
PyCharm creates a separate virtual environment (venv) for each project by default. This environment is isolated from your system's global Python interpreter, so any libraries you install here only exist in this venv. When you run python mcdis.py directly from Windows, it uses the global interpreter (which doesn't have discord installed), hence the ModuleNotFoundError.
内容的提问来源于stack exchange,提问作者Andrei Popa

