本文整理 Python 開發中常用的片段、模組用法、編碼設定、C 擴充呼叫等實用技巧,適合作為開發時的速查參考。
# -*- coding: UTF-8 -*-
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]
try:
import json
except ImportError:
import simplejson as json
# Python 2.7 以下
echo '{"hello":1}' | python -m simplejson.tool
# Python 2.7+ / 3.x
echo '{"hello":1}' | python -m json.tool
Py_Initialize();
PyObject* pModule = PyImport_ImportModule("mytest");
PyObject* pFunc = PyObject_GetAttrString(pModule, "test1");
PyObject* pResult = PyObject_CallFunction(pFunc, "is", 2, "hello");
// ... 處理結果 ...
Py_Finalize();
#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;
}
def test1(s, str):
print(s + str)
return 0
def test2(s):
return s
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 |
| json | JSON 序列化 | 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__ 減少實例記憶體佔用。multiprocessing 或 Cython/Numba。