Python解释器安装

访问Python官方网站(https://www.python.org/downloads/),选择与操作系统匹配的最新稳定版本下载。Windows用户需勾选"Add Python to PATH"选项,确保命令行可直接调用Python。MacOS系统默认预装Python 2.7,建议通过Homebrew安装新版:brew install python。Linux用户可通过包管理器安装,例如Ubuntu使用sudo apt install python3

验证安装成功需在终端执行:

python --version
pip --version

PyCharm安装配置

从JetBrains官网(https://www.jetbrains.com/pycharm/download/)下载Community(免费)或Professional版。Windows用户运行.exe安装程序时建议创建桌面快捷方式。MacOS需将应用拖入Applications文件夹,Linux用户解压后运行pycharm.sh脚本。首次启动时选择UI主题,安装常用插件如Markdown、Database Tools。

创建新项目时指定Python解释器路径,虚拟环境推荐使用venv:

python -m venv myenv
source myenv/bin/activate  # Linux/Mac
myenv\Scripts\activate.bat  # Windows

开发环境优化

调整PyCharm字体和配色方案(File > Settings > Editor > Font)。启用版本控制集成(VCS > Enable Version Control Integration),配置Git/GitHub。安装代码质量工具(File > Settings > Tools > External Tools)如flake8和black。

调试配置示例:

# 添加断点后使用Debug模式运行
def calculate(x):
    return x * 2

if __name__ == '__main__':
    result = calculate(5)
    print(result)

包管理实践

使用requirements.txt管理依赖:

pip freeze > requirements.txt
pip install -r requirements.txt

对于复杂项目推荐setup.py:

from setuptools import setup

setup(
    name="project",
    version="0.1",
    install_requires=[
        'numpy>=1.18',
        'pandas<2.0'
    ]
)

项目结构规范

标准Python项目目录示例:

my_project/
├── docs/
├── tests/
│   └── test_main.py
├── src/
│   └── __init__.py
├── .gitignore
├── LICENSE
└── README.md

配置.gitignore排除编译文件:

__pycache__/
*.py[cod]
*.egg-info/
dist/

测试与部署

使用unittest或pytest编写测试用例:

import unittest

class TestCalc(unittest.TestCase):
    def test_add(self):
        self.assertEqual(1+1, 2)

通过setup.py打包项目:

python setup.py sdist bdist_wheel
twine upload dist/*

性能调优技巧

使用cProfile分析代码性能:

import cProfile

def slow_function():
    total = 0
    for i in range(10**6):
        total += i
    return total

cProfile.run('slow_function()')

考虑Cython加速关键代码:

# save as fast.pyx
def compute(int n):
    cdef int i, total=0
    for i in range(n):
        total += i
    return total

虚拟环境进阶

使用pipenv管理依赖:

pip install pipenv
pipenv install requests
pipenv shell

多Python版本管理(Linux/Mac):

pyenv install 3.9.0
pyenv global 3.9.0

异常处理实践

结构化异常处理示例:

try:
    with open('data.txt') as f:
        content = f.read()
except FileNotFoundError as e:
    print(f"Error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
else:
    process(content)
finally:
    cleanup_resources()

自定义异常类:

class APIError(Exception):
    def __init__(self, status_code):
        self.status_code = status_code
        super().__init__(f"API failed with {status_code}")

文档字符串规范

遵循PEP257编写文档:

def quadratic(a, b, c):
    """Solve quadratic equation ax² + bx + c = 0.
    
    Args:
        a: Coefficient of x²
        b: Coefficient of x
        c: Constant term
    
    Returns:
        Tuple of two solutions
    """
    discriminant = b**2 - 4*a*c
    x1 = (-b + discriminant**0.5) / (2*a)
    x2 = (-b - discriminant**0.5) / (2*a)
    return x1, x2

生成HTML文档:

pip install sphinx
sphinx-quickstart docs

并发编程基础

多线程示例:

from threading import Thread
import time

def task(name):
    print(f"Start {name}")
    time.sleep(2)
    print(f"End {name}")

threads = [Thread(target=task, args=(i,)) for i in range(3)]
for t in threads:
    t.start()
for t in threads:
    t.join()

异步IO示例:

import asyncio

async def fetch_data():
    print("Start fetching")
    await asyncio.sleep(2)
    print("Done fetching")
    return {'data': 1}

async def main():
    task = asyncio.create_task(fetch_data())
    result = await task
    print(result)

asyncio.run(main())

数据库交互

SQLite基础操作:

import sqlite3

conn = sqlite3.connect('test.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users
               (id INTEGER PRIMARY KEY, name TEXT)''')
cursor.execute("INSERT INTO users VALUES (1, 'Alice')")
conn.commit()
conn.close()

使用SQLAlchemy ORM:

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('sqlite:///test.db')

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)

Base.metadata.create_all(engine)

Web开发基础

Flask最小应用:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return "Hello World"

if __name__ == '__main__':
    app.run(debug=True)

FastAPI示例:

from fastapi import FastAPI
app = FastAPI()

@app.get("/items/{item_id}")
async def read_item(item_id: int):
    return {"item_id": item_id}

数据分析基础

Pandas数据处理:

import pandas as pd

data = {'Name': ['Alice', 'Bob'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df[df['Age'] > 26])

Matplotlib可视化:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.title('Sine Wave')
plt.show()

机器学习入门

Scikit-learn线性回归:

from sklearn.linear_model import LinearRegression
import numpy as np

X = np.array([[1], [2], [3]])
y = np.array([2, 4, 6])
model = LinearRegression().fit(X, y)
print(model.predict([[4]]))

TensorFlow神经网络:

import tensorflow as tf

model = tf.keras.Sequential([
    tf.keras.layers.Dense(10, input_shape=(4,), activation='relu'),
    tf.keras.layers.Dense(1)
])
model.compile(optimizer='adam', loss='mse')

打包发布

创建PyPI账户后生成API token,配置~/.pypirc

[pypi]
username = __token__
password = pypi-your-api-token

使用twine上传:

pip install twine
python setup.py sdist bdist_wheel
twine upload dist/*

持续集成

GitHub Actions示例(.github/workflows/test.yml):

name: Python CI
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Set up Python
      uses: actions/setup-python@v2
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt
    - name: Run tests
      run: |
        python -m pytest

Logo

小龙虾开发者社区是 CSDN 旗下专注 OpenClaw 生态的官方阵地,聚焦技能开发、插件实践与部署教程,为开发者提供可直接落地的方案、工具与交流平台,助力高效构建与落地 AI 应用

更多推荐