"""Offline Python verification lab for PyCharm Chapter 07 (new-project)."""
import argparse
import importlib.util
import json
import shlex
import tempfile
import tomllib
import xml.etree.ElementTree as ET
from pathlib import Path
VERSION = "CPython 3.12.14 offline PyCharm workflow verifier (desktop IDE not launched)"
def case_project_tree_and_venv_isolation():
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "my_project"
(root / ".idea").mkdir(parents=True)
(root / "venv").mkdir()
(root / "main.py").write_text('print("Hello, World!")\n', encoding="utf-8")
(root / "utils.py").write_text("def add(a, b): return a + b\n", encoding="utf-8")
excluded = {".idea", "venv"}
shareable = sorted(p.name for p in root.iterdir() if p.name not in excluded)
py_files = sorted(p.name for p in root.glob("*.py"))
expected = {
"venv_stdlib_available": True,
"has_idea_dir": True,
"has_venv_dir": True,
"shareable_files": ["main.py", "utils.py"],
"python_files": ["main.py", "utils.py"],
}
actual = {
"venv_stdlib_available": importlib.util.find_spec("venv") is not None,
"has_idea_dir": (root / ".idea").is_dir(),
"has_venv_dir": (root / "venv").is_dir(),
"shareable_files": shareable,
"python_files": py_files,
}
return {
"name": "project_tree_and_venv_isolation",
"summary": "校验默认项目目录结构(.idea/、venv/、main.py)、标准库 venv 模块及备份排除规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_run_debug_configuration_xml():
run_cfg_xml = """<component name="ProjectRunConfigurationManager">
<configuration default="false" name="main" type="PythonConfigurationType" factoryName="Python">
<option name="SCRIPT_NAME" value="$PROJECT_DIR$/main.py" />
<option name="PARAMETERS" value="--port 8000" />
<option name="SDK_HOME" value="$PROJECT_DIR$/venv/Scripts/python.exe" />
</configuration>
</component>"""
root = ET.fromstring(run_cfg_xml)
opts = {o.attrib["name"]: o.attrib["value"] for o in root.findall(".//option")}
parser = argparse.ArgumentParser()
parser.add_argument("--port", type=int, required=True)
ns = parser.parse_args(shlex.split(opts["PARAMETERS"]))
expected = {
"script_suffix": ".py",
"parsed_port": 8000,
"uses_venv_sdk": True,
}
actual = {
"script_suffix": Path(opts["SCRIPT_NAME"]).suffix,
"parsed_port": ns.port,
"uses_venv_sdk": "venv" in opts["SDK_HOME"],
}
return {
"name": "run_debug_configuration_xml",
"summary": "解析 .idea 运行/调试配置 XML 并用 argparse 验证 --port 8000 参数传递",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_dependency_manifest_parsing():
req_txt = "# core deps\nrequests==2.32.3\nflask>=3.0.0\n"
pyproject_toml = """
[project]
name = "my-project"
version = "0.1.0"
dependencies = ["requests==2.32.3", "flask>=3.0.0"]
"""
req_lines = [ln.strip() for ln in req_txt.splitlines() if ln.strip() and not ln.strip().startswith("#")]
parsed_toml = tomllib.loads(pyproject_toml)
toml_deps = parsed_toml["project"]["dependencies"]
pip_cmds = ["pip install -r requirements.txt", "pip freeze > requirements.txt"]
expected = {
"requirements_count": 2,
"toml_matches_requirements": True,
"pip_cmd_count": 2,
}
actual = {
"requirements_count": len(req_lines),
"toml_matches_requirements": toml_deps == req_lines,
"pip_cmd_count": len(pip_cmds),
}
return {
"name": "dependency_manifest_parsing",
"summary": "使用 tomllib 与文本解析校验 pyproject.toml、requirements.txt 一致性及 pip 导出/安装命令",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_project_lifecycle_and_settings():
ops = {
"close": "文件 → 关闭项目(File → Close Project)",
"interpreter_settings": "文件 → 设置 → Python 解释器",
"multi_project": "new_window_or_attach",
"delete_policy": "close_then_delete_folder_manually",
}
expected = {
"op_count": 4,
"safe_delete_manual": True,
"has_close_menu": True,
}
actual = {
"op_count": len(ops),
"safe_delete_manual": ops["delete_policy"] == "close_then_delete_folder_manually",
"has_close_menu": "Close Project" in ops["close"],
}
return {
"name": "project_lifecycle_and_settings",
"summary": "核对多项目窗口打开、关闭项目、解释器切换与手动删除项目的操作规程",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_project_tree_and_venv_isolation(),
case_run_debug_configuration_xml(),
case_dependency_manifest_parsing(),
case_project_lifecycle_and_settings(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。
入口文件:projects/pycharm-new-project-lab/explore-new-project.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-new-project.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线 PyCharm 工程语义与配置验证器(未启动桌面端 PyCharm IDE)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联17章) · 含当前章节或实例 · mbskycom202612a2240.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2250.zip