强曰为道

与天地相似,故不违。知周乎万物,而道济天下,故不过。旁行而不流,乐天知命,故不忧.
文档目录

03 - Hello World

第 03 章:Hello World

从第一行代码开始,掌握 Python 的交互式和脚本运行方式。


3.1 交互式 REPL

3.1.1 启动 REPL

# 启动 Python 交互式解释器
$ python3
Python 3.12.4 (main, Jun  8 2024, 18:29:57) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

3.1.2 基本操作

>>> print("Hello, World!")
Hello, World!

>>> 2 + 3
5

>>> "Hello" + " " + "Python"
'Hello Python'

>>> exit()  # 或 Ctrl+D 退出

3.1.3 REPL 特殊变量

>>> _          # 上一次表达式的结果
>>> 2 + 3
5
>>> _ * 2
10

>>> help()     # 进入帮助系统
>>> dir([])    # 查看对象属性
>>> type(42)   # 查看类型
<class 'int'>

3.1.4 增强 REPL

工具特点
IPython语法高亮、自动补全、魔术命令
bpython实时自动补全、语法高亮
ptpythonVi/Emacs 键绑定、自动补全
# 安装 IPython
$ pip install ipython

# 启动
$ ipython
In [1]: "hello".upper()
Out[1]: 'HELLO'

3.2 脚本运行

3.2.1 第一个脚本

创建 hello.py

#!/usr/bin/env python3
"""我的第一个 Python 脚本。"""

def greet(name: str) -> str:
    """生成问候语。"""
    return f"Hello, {name}! Welcome to Python."

if __name__ == "__main__":
    print(greet("World"))

运行脚本:

$ python3 hello.py
Hello, World! Welcome to Python.

3.2.2 Shebang 行

#!/usr/bin/env python3  # 推荐写法
#!/usr/bin/python3      # 不推荐(路径可能不同)

使用 shebang 使脚本可直接执行:

$ chmod +x hello.py
$ ./hello.py
Hello, World! Welcome to Python.

3.2.3 __name__ 的作用

运行方式__name__ 的值
python hello.py"__main__"
import hello"hello"
# mymodule.py
def add(a: int, b: int) -> int:
    return a + b

if __name__ == "__main__":
    # 只在直接运行时执行,导入时不执行
    print(add(1, 2))

3.2.4 命令行参数

# args_demo.py
import sys

if __name__ == "__main__":
    print(f"脚本名称: {sys.argv[0]}")
    print(f"参数列表: {sys.argv[1:]}")
$ python3 args_demo.py hello world
脚本名称: args_demo.py
参数列表: ['hello', 'world']

3.2.5 -c-m 选项

# 直接执行代码
$ python3 -c "print('Hello')"

# 运行模块
$ python3 -m http.server 8000

# 运行包
$ python3 -m pytest

# 查看模块位置
$ python3 -m site

3.3 编码规范(PEP 8)

3.3.1 命名规范

类型规范示例
变量snake_caseuser_name, max_retry
常量UPPER_SNAKE_CASEMAX_SIZE, API_KEY
函数snake_caseget_user(), send_email()
PascalCaseUserModel, HttpClient
模块snake_caseutils.py, db_models.py
snake_casemypackage
私有前导下划线_internal, __mangled

3.3.2 格式规范

# ✅ 正确
x = 1
y = 2
long_variable_name = "hello"

# ❌ 错误
x             = 1
y             = 2
longVarName   = "hello"

# ✅ 函数之间空两行
def first_function():
    pass


def second_function():
    pass

# ✅ 类中方法之间空一行
class MyClass:
    def method_one(self):
        pass

    def method_two(self):
        pass

3.3.3 导入规范

# ✅ 每个模块单独导入
import os
import sys
from pathlib import Path

# ❌ 一行导入多个
import os, sys

# 导入顺序(PEP 8 推荐):
# 1. 标准库
import os
import sys

# 2. 第三方库
import requests
import pandas as pd

# 3. 本地模块
from myproject.utils import helper

3.3.4 行长度与换行

# 行长度限制 79 字符(严格)或 88 字符(Black/Ruff 默认)

# 使用括号换行
result = some_function(
    first_argument,
    second_argument,
    third_argument,
)

# 使用反斜杠换行(不推荐)
result = first_value + \
         second_value + \
         third_value

3.3.5 自动格式化工具

# Ruff(推荐,速度极快)
$ pip install ruff
$ ruff format my_script.py
$ ruff check my_script.py

# Black
$ pip install black
$ black my_script.py

# isort(排序导入)
$ pip install isort
$ isort my_script.py

3.4 模块系统基础

3.4.1 导入模块

# 导入整个模块
import math
print(math.pi)  # 3.141592653589793

# 导入特定成员
from math import pi, sqrt
print(pi)
print(sqrt(16))  # 4.0

# 别名导入
import numpy as np
from datetime import datetime as dt

# 导入所有(不推荐,污染命名空间)
from math import *

3.4.2 标准库常用模块

模块用途示例
os操作系统交互os.path.join()
sys系统参数sys.argv, sys.path
math数学函数math.sqrt(), math.ceil()
datetime日期时间datetime.now()
jsonJSON 解析json.dumps(), json.loads()
pathlib路径操作Path("dir/file.txt")
re正则表达式re.match()
collections高级容器Counter, defaultdict
itertools迭代工具chain(), product()
functools函数工具lru_cache(), partial()

3.4.3 使用标准库

# 日期时间
from datetime import datetime, timezone

now = datetime.now(timezone.utc)
print(now.strftime("%Y-%m-%d %H:%M:%S"))

# 随机数
import random
print(random.randint(1, 100))
print(random.choice(["apple", "banana", "cherry"]))

# 计时
import time
start = time.perf_counter()
# 执行某些操作
result = sum(range(1_000_000))
elapsed = time.perf_counter() - start
print(f"耗时: {elapsed:.4f} 秒")

3.5 注释与文档

3.5.1 注释类型

# 单行注释
x = 42  # 行末注释

"""
多行注释
(实际上是多行字符串字面量,但常用作注释)
"""

def calculate_area(radius: float) -> float:
    """计算圆的面积。

    Args:
        radius: 圆的半径,必须为正数。

    Returns:
        圆的面积。

    Raises:
        ValueError: 当半径为负数时。
    """
    if radius < 0:
        raise ValueError("半径不能为负数")
    return 3.14159 * radius ** 2

3.5.2 docstring 风格

Google 风格(推荐):

def fetch_user(user_id: int) -> dict:
    """从数据库获取用户信息。

    Args:
        user_id: 用户的唯一标识符。

    Returns:
        包含用户信息的字典,格式如下:
        {
            "id": int,
            "name": str,
            "email": str,
        }

    Raises:
        UserNotFoundError: 用户不存在时。
    """
    ...

3.6 编码与 Unicode

3.6.1 源文件编码

# Python 3 源文件默认 UTF-8 编码
# 以下声明在 Python 3 中通常不需要
# -*- coding: utf-8 -*-

# 直接使用中文
message = "你好,世界!"
print(message)

3.6.2 字符编码基础

概念说明
ASCII128 个字符,英文和数字
UTF-8可变长度,兼容 ASCII,推荐
Unicode字符集标准
# 编码转换
text = "你好"
encoded = text.encode("utf-8")   # b'\xe4\xbd\xa0\xe5\xa5\xbd'
decoded = encoded.decode("utf-8")  # '你好'

# 查看码点
print(ord("你"))   # 20320
print(chr(20320))  # '你'

3.7 注意事项

🔴 注意

  • Python 区分大小写:nameNameNAME 是三个不同的标识符
  • 缩进使用 4 个空格,不要使用 Tab
  • 避免使用 lOI 作为变量名(易与数字混淆)
  • Python 3 不兼容 Python 2 的 print 语句

💡 提示

  • 使用 type() 检查变量类型
  • 使用 dir() 查看对象属性
  • 使用 help() 查看文档
  • 推荐使用 ruff 代替 black + isort + flake8

📌 业务场景: 编写自动化运维脚本时,规范的项目结构和良好的编码习惯至关重要:

#!/usr/bin/env python3
"""服务器健康检查脚本。"""

import sys
import psutil
from datetime import datetime

def check_cpu(threshold: float = 80.0) -> bool:
    """检查 CPU 使用率是否超过阈值。"""
    usage = psutil.cpu_percent(interval=1)
    status = "⚠️" if usage > threshold else "✅"
    print(f"{status} CPU: {usage}%")
    return usage <= threshold

def check_memory(threshold: float = 80.0) -> bool:
    """检查内存使用率是否超过阈值。"""
    mem = psutil.virtual_memory()
    status = "⚠️" if mem.percent > threshold else "✅"
    print(f"{status} 内存: {mem.percent}% ({mem.used // (1024**3)}GB / {mem.total // (1024**3)}GB)")
    return mem.percent <= threshold

def check_disk(path: str = "/", threshold: float = 90.0) -> bool:
    """检查磁盘使用率是否超过阈值。"""
    disk = psutil.disk_usage(path)
    status = "⚠️" if disk.percent > threshold else "✅"
    print(f"{status} 磁盘 {path}: {disk.percent}%")
    return disk.percent <= threshold

if __name__ == "__main__":
    print(f"=== 服务器健康检查 {datetime.now():%Y-%m-%d %H:%M} ===")
    results = [check_cpu(), check_memory(), check_disk()]
    sys.exit(0 if all(results) else 1)

3.8 扩展阅读