已配置Anaconda环境,PyCharm中仍无法导入PyTorch怎么办?
Hey there! I’ve run into this exact problem before—Anaconda has PyTorch installed, but PyCharm just won’t recognize it. Let’s walk through the most common fixes step by step:
1. Double-Check PyCharm is Using the Correct Anaconda Environment
This is the #1 culprit. Here’s how to verify and fix it:
- Open PyCharm, go to
File > Settings > Project: [Your Project Name] > Python Interpreter(on Mac, it’sPyCharm > Settings > ...) - Look at the dropdown at the top—this should be the Anaconda environment where you installed PyTorch (e.g.,
baseor a custom env you created) - If it’s not the right one:
- Click the gear icon >
Add - Select
Conda Environment>Existing environment - Browse to your Anaconda installation folder, then navigate to
envs/[Your Env Name]/python.exe(Windows) orenvs/[Your Env Name]/bin/python(Mac/Linux) - Hit
OKand apply the settings
- Click the gear icon >
2. Confirm PyTorch is Actually Installed in Your Anaconda Env
Let’s make sure the environment has PyTorch first:
- Open Anaconda Prompt (Windows) or your terminal (Mac/Linux)
- Activate your environment with:
conda activate [Your Env Name] - Run
conda list torch—you should see a line withtorchand its version number - If it’s missing, reinstall PyTorch in this env (use the command matching your system, e.g., for CPU-only:
conda install pytorch torchvision torchaudio cpuonly -c pytorch)
3. Refresh PyCharm’s Package Cache
PyCharm sometimes doesn’t auto-detect new packages. Here’s how to force a refresh:
- Go back to the
Python Interpretersettings page - Click the circular refresh icon in the top-right corner of the package list
- Wait for PyCharm to scan the environment again—you should see
torchpop up in the package list once it’s done
4. Ensure No Project-Specific Virtual Environment is Interfering
When creating a new project, PyCharm might default to making a fresh virtual environment instead of using your Anaconda env:
- If you already created the project, follow step 1 to switch to the correct Anaconda environment
- For future projects, when setting up, select
Previously configured interpreterand pick your Anaconda env from the list
5. Restart PyCharm
Sometimes the simplest fix works! Close PyCharm completely, reopen it, and try running import torch again. More often than not, this clears up any lingering cache issues.
Give these steps a try—they should get PyCharm and your Anaconda PyTorch environment talking again!
内容的提问来源于stack exchange,提问作者Midoril

