首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Python 實用技巧與常用模組速查手冊

     編輯:PHP 相關知識

前言

本文整理 Python 開發中常用的片段、模組用法、編碼設定、C 擴充呼叫等實用技巧,適合作為開發時的速查參考。

一、基礎環境設定

原始碼編碼宣告 (Python 2 必須,Python 3 預設 UTF-8)

# -*- coding: UTF-8 -*-

二、系統互動與路徑處理

執行 Shell 指令並取得輸出

from subprocess import Popen, PIPE

def run_cmd(cmd):
    child = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
    out, err = child.communicate()
    ret = child.wait()
    return (ret, out, err)

取得目前腳本所在目錄

import os
script_dir = os.path.split(os.path.realpath(__file__))[0]

三、JSON 處理

相容性匯入 (支援舊版 simplejson)

try:
    import json
except ImportError:
    import simplejson as json

命令列美化 JSON 輸出

# Python 2.7 以下
echo '{"hello":1}' | python -m simplejson.tool

# Python 2.7+ / 3.x
echo '{"hello":1}' | python -m json.tool

四、嵌入 Python 於 C/C++ 專案

標準呼叫流程

Py_Initialize();
PyObject* pModule = PyImport_ImportModule("mytest");
PyObject* pFunc = PyObject_GetAttrString(pModule, "test1");
PyObject* pResult = PyObject_CallFunction(pFunc, "is", 2, "hello");
// ... 處理結果 ...
Py_Finalize();

完整 C 範例 (編譯需連結 libpython)

#include <python2.7/Python.h>

int main() {
    PyObject *pModule = NULL;
    Py_Initialize();
    if (!Py_IsInitialized()) { printf("init error\n"); return -1; }

    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('./')");

    pModule = PyImport_ImportModule("mytest");
    if (!pModule) { printf("Cant open python file!\n"); return -2; }

    PyObject *pFunc = PyObject_GetAttrString(pModule, "test1");
    PyObject *pResult = PyObject_CallFunction(pFunc, "is", 2, "hello");
    if (!pResult) { printf("invoke function fail\n"); }

    PyObject *pFunc2 = PyObject_GetAttrString(pModule, "test2");
    pResult = PyObject_CallFunction(pFunc2, "i", 2);
    char *str = PyString_AsString(pResult);
    printf("%s\n", str);

    Py_Finalize();
    return 0;
}

對應 Python 模組 (mytest.py)

def test1(s, str):
    print(s + str)
    return 0

def test2(s):
    return s

編譯指令 (假設 Python 安裝於 /opt/python)

gcc -I/opt/python/include -L/opt/python/lib -lpython2.7 test.c -o test

# Python 必須啟用 shared library 編譯
./configure --prefix=/opt/python --enable-shared

五、常用標準庫速查

模組用途常用函數/類別
os / os.path檔案系統、路徑操作path.join, listdir, makedirs, walk
sys執行環境參數argv, path, exit, version_info
subprocess子行程管理run, Popen, check_output
jsonJSON 序列化dumps, loads, load, dump
datetime日期時間now, strftime, strptime, timedelta
re正則表達式match, search, findall, sub
collections進階資料結構defaultdict, Counter, OrderedDict, namedtuple
itertools迭代器工具chain, cycle, islice, permutations
functools高階函數lru_cache, partial, reduce, wraps

六、效能優化小撇步

  • 區域變數存取比全域變數快,函數內常用 local_var = global_obj.method 快取。
  • 大量字串拼接使用 ''.join(list) 而非 +=。
  • 迴圈中避免重複屬性查找:for x in data: process(x.attr) → attr = x.attr; process(attr)。
  • 使用 __slots__ 減少實例記憶體佔用。
  • CPU 密集型任務考慮 multiprocessing 或 Cython/Numba。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved