Win10系统Python3.10环境下运行含numpy的.py文件报错,但命令行交互模式正常的问题求助
Hey Pavel, I’ve run into similar weird environment mismatches before—let’s break down what’s going on and fix this step by step. The key clue here is that numpy works in the interactive shell but fails in a script, which points to a Python environment mismatch or standard library interference, not an issue with numpy itself.
Step 1: Check for Conflicting Filenames
First, make sure you don’t have any files in your script directory (C:\TESTY\PY4E) that share names with Python’s standard library modules. For example:
- Do you have an
os.pyorsocket.pyfile here? - Also check for compiled
.pycversions of these files.
If you find any, delete them immediately. Python prioritizes files in the current working directory over the system’s standard library, so having a custom os.py would break all imports of the real os module.
Step 2: Ensure You’re Running the Correct Python Version
Sometimes multiple Python versions are installed on Windows, and the python command might point to a different version than the interactive shell.
- Open Command Prompt and run:
python --version - Compare this to the version you see when you launch the interactive shell (it should say Python 3.10.x).
- If they don’t match, run your script explicitly with Python 3.10:
Thepy -3.10 numpy_test.pypylauncher is the safest way to target specific Python versions on Windows.
Step 3: Repair Python’s Standard Library and Numpy
Your error traces show issues with platform.py and the socket module, which suggests either a corrupted standard library or a broken numpy installation:
- Force-reinstall numpy to ensure it’s properly linked to your Python 3.10 installation:
py -3.10 -m pip install --force-reinstall numpy - If that doesn’t work, check if your
platform.pyfile is modified. Navigate toC:\Users\pawel\AppData\Local\Programs\Python\Python310\lib\platform.pyand verify theuname()function has fallback logic for Windows (sinceos.uname()doesn’t exist on Windows). If the file looks tampered with, do a clean reinstall of Python 3.10:- Uninstall Python via Settings > Apps > Apps & Features.
- Delete the
Python310folder atC:\Users\pawel\AppData\Local\Programs\Python. - Delete the
Python310folder atC:\Users\pawel\AppData\Roaming\Python. - Download the official Python 3.10 installer, check "Add Python to PATH", and do a full installation.
Step 4: Test a Minimal Script to Isolate the Issue
Create a tiny script called test_env.py with this content:
import os import socket print("OS module name:", os.name) print("Hostname:", socket.gethostname())
Run it with py -3.10 test_env.py. If this throws the same AttributeError, the problem is definitely with your Python standard library, not numpy. In that case, the clean reinstall from Step 3 is your best bet.
内容的提问来源于stack exchange,提问作者PavelS

