
本文详解为何直接在PowerShell或Windows命令行中执行Python代码会报错,并指导读者搭建合适的Python环境(如VS Code、Jupyter Notebook等),以正确导入sklearn.model_selection.train_test_split等模块完成数据分析与预测任务。
本文详解为何直接在powershell或windows命令行中执行python代码会报错,并指导读者搭建合适的python环境(如vs code、jupyter notebook等),以正确导入`sklearn.model_selection.train_test_split`等模块完成数据分析与预测任务。
你遇到的错误:
The 'from' keyword is not supported in this version of the language.
根本原因:你当前并非在 Python 解释器中运行代码,而是在 PowerShell(或 CMD/Windows Terminal)这类Shell 环境下直接输入了 Python 语法。PowerShell 是 Windows 的命令行外壳,它识别的是 PowerShell 命令(如 Get-Process),而非 Python 关键字(如 from、import、def)。因此,当你键入 from sklearn.model_selection import train_test_split 时,PowerShell 将其视为非法语法,触发 ReservedKeywordNotAllowed 解析错误。
✅ 正确做法是:先启动 Python 环境,再执行 Python 代码。
✅ 推荐的 Python 运行方式(任选其一)
1. 使用交互式 Python 解释器(适合快速验证)
在终端中先输入 python 或 python3 启动解释器(确保已安装 Python 并配置环境变量):
立即学习“Python免费学习笔记(深入)”;
PS C:\> python
Python 3.11.8 (main, Mar 5 2024, 12:37:17) [MSC v.1938 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from sklearn.model_selection import train_test_split
>>> print("✅ 导入成功!")
✅ 导入成功!
>>>? 提示:输入 exit() 或按 Ctrl+Z + Enter 退出解释器。
2. 使用 .py 脚本文件(适合完整分析流程)
创建 data_analysis.py 文件,写入完整代码:
# data_analysis.py
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
# 示例:模拟加载数据
df = pd.DataFrame({
'feature1': [1, 2, 3, 4, 5],
'feature2': [10, 20, 30, 40, 50],
'target': [15, 25, 35, 45, 55]
})
X = df[['feature1', 'feature2']]
y = df['target']
# 划分训练集与测试集
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
print(f"训练集大小: {X_train.shape}, 测试集大小: {X_test.shape}")然后在终端中运行:
PS C:\project> python data_analysis.py 训练集大小: (4, 2), 测试集大小: (1, 2)
3. 使用 Jupyter Notebook(强烈推荐用于数据分析与预测建模)
- 安装:pip install jupyter
- 启动:jupyter notebook → 自动打开浏览器界面
- 在单元格中直接写入并运行 Python 代码(支持可视化、分步调试、Markdown 注释):
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
4. 使用 VS Code(专业开发首选)
- 安装 Python 扩展;
- 按 Ctrl+Shift+P → 输入 Python: Select Interpreter,选择已安装的 Python 环境;
- 新建 .py 文件或 .ipynb 文件,右键选择 Run Python File in Terminal 即可执行。
⚠️ 注意事项
- ❌ 不要在 PowerShell/CMD 中直接写 from ... import ... —— 这不是 Python 环境;
- ✅ 确保已安装 scikit-learn:pip install scikit-learn(若提示 ModuleNotFoundError);
- ✅ 检查 Python 版本 ≥ 3.8(scikit-learn 1.2+ 要求);
- ✅ 推荐使用虚拟环境隔离项目依赖:
python -m venv myenv myenv\Scripts\activate pip install pandas scikit-learn matplotlib
掌握正确的执行环境,是开展 Python 数据分析与机器学习预测的第一步。从今天起,请始终确认自己处于 Python 解释器、.py 脚本或 Jupyter Notebook 中——而不是 Shell 命令行里。


















