PyCharm 第一个 Python
演示如何通过欢迎页快捷新建脚本或完整新建项目流程编写并运行第一个 Python 程序,同时说明项目设置入口以及未配置解释器与安装第三方库两项高频问答。
学完这一章,你能够
- 演示如何通过欢迎页快捷新建脚本或完整新建项目流程编写并运行第一个 Python 程序,同时说明项目设置入口以及未配置解释器与安装第三方库两项高频问答。
从欢迎界面快速新建脚本体验
启动 PyCharm 后,欢迎界面直接提供了多种高频快捷入口。如果只想迅速验证一段独立代码,可直接点击“新建脚本”按钮,PyCharm 会自动生成 `script.py` 并初始化基础运行环境;随后在编辑器中修改代码并点击运行,即可在底部运行控制台即时查看输出结果。
通过新建项目创建并运行首个脚本
面向正式工程开发时,推荐先建立独立项目:在欢迎界面点击“新建项目(New Project)”,输入规范的项目名称(例如 `hello_pycharm_project`)、设定本地存储路径并选定 Python 解释器后点击“创建(Create)”。项目打开后,在左侧项目树根目录右键选择“新建 → Python 文件”,输入文件名(例如 `hello_demo.py`,无需手写 `.py` 后缀也会自动补齐)即可生成首个源码文件。
在新建的 Python 文件中写入一条输出语句(例如 `print("Hello, PyCharm!")`),随后即可通过两种方式执行:点击主窗口右上角的绿色运行按钮,或在编辑器空白处右键选择“运行 '<脚本名>'”。本站离线验证脚本在临时目录完整创建了上述项目结构与入口脚本,并通过当前 CPython 3.12.14 真实执行确认输出与退出码 `0`。
项目设置与新手常见问题解答
项目初始化完成后,点击界面右上角的齿轮设置图标即可随时打开设置面板,按需调整编辑器字体、编码、配色方案或切换当前项目绑定的 Python 解释器。
新手最常遇到的第一个问题是启动后提示 `No Python interpreter configured`,表明 PyCharm 未能自动定位 Python 解释器。解决办法为:在 Windows/Linux 打开“文件 → 设置”(macOS 为“PyCharm → 设置”),在左侧展开“项目: <项目名称> → Python 解释器”,点击右上角“添加解释器”,浏览选择已安装的 Python 可执行文件或新建虚拟环境即可。
第二个常见问题是如何安装第三方库:同样通过“File → Settings”(macOS 为“PyCharm → Preferences/Settings”)进入“项目: <项目名称> → Python 解释器”,点击包列表区域的 `+` 按钮,在弹窗中搜索目标包名并执行安装,PyCharm 会自动将其装入当前项目解释器环境。
离线创建首个 Python 项目目录、执行问候脚本并校验 .idea 解释器绑定 XML
展开查看收起
"""Offline Python verification lab for PyCharm Chapter 05 (first-python-project)."""
import json
import subprocess
import sys
import tempfile
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_create_first_project_and_script():
with tempfile.TemporaryDirectory() as tmp:
proj = Path(tmp) / "hello_pycharm_project"
(proj / ".idea").mkdir(parents=True)
script = proj / "hello_demo.py"
script.write_text('print("Hello, PyCharm!")\n', encoding="utf-8")
proc = subprocess.run(
[sys.executable, "-I", "-B", "-X", "utf8", str(script)],
cwd=proj,
capture_output=True,
encoding="utf-8",
timeout=15,
)
expected = {
"project_dir_exists": True,
"script_name": "hello_demo.py",
"returncode": 0,
"stdout": "Hello, PyCharm!\n",
}
actual = {
"project_dir_exists": (proj / ".idea").is_dir(),
"script_name": script.name,
"returncode": proc.returncode,
"stdout": proc.stdout,
}
return {
"name": "create_first_project_and_script",
"summary": "在临时目录创建首个 Python 项目结构与入口脚本并实际执行,校验标准输出与退出码 0",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_interpreter_xml_binding():
unconfigured = '<project version="4"><component name="ProjectRootManager" /></project>'
configured = (
'<project version="4">'
'<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.12 (hello_pycharm_project)" project-jdk-type="Python SDK" />'
"</project>"
)
def inspect_jdk(xml_text):
node = ET.fromstring(xml_text).find("./component[@name='ProjectRootManager']")
return node.attrib.get("project-jdk-name") if node is not None else None
expected = {
"before_missing": True,
"after_jdk": "Python 3.12 (hello_pycharm_project)",
}
actual = {
"before_missing": inspect_jdk(unconfigured) is None,
"after_jdk": inspect_jdk(configured),
}
return {
"name": "interpreter_xml_binding",
"summary": "模拟 .idea/misc.xml 从未配置解释器到绑定 Python 3.12 解释器的状态变化",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_third_party_package_install_spec():
settings_paths = {
"Windows/Linux": "File -> Settings -> Project -> Python Interpreter -> +",
"macOS": "PyCharm -> Preferences/Settings -> Project -> Python Interpreter -> +",
}
expected = {
"platform_count": 2,
"uses_plus_button": True,
}
actual = {
"platform_count": len(settings_paths),
"uses_plus_button": all(v.endswith("+") for v in settings_paths.values()),
}
return {
"name": "third_party_package_install_spec",
"summary": "核对 Windows/Linux 与 macOS 在项目解释器界面添加第三方库的标准入口路径",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_create_first_project_and_script(),
case_interpreter_xml_binding(),
case_third_party_package_install_spec(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
既可以点击窗口右上角工具栏的绿色运行按钮,也可以在代码编辑区右键并选择“运行 '<脚本名>'”。