整理 Python 開發中高頻使用的片段,涵蓋編碼宣告、子進程執行、腳本路徑、JSON 相容匯入、CLI 格式化、C/C++ 擴展調用流程與編譯參數。
# -*- coding: utf-8 -*-
Python 3 預設 UTF-8,通常可省略。
from subprocess import Popen, PIPE
def run_cmd(cmd: str) -> tuple[int, str, str]:
"""回傳 (return_code, stdout, stderr)"""
child = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True, text=True)
out, err = child.communicate()
return child.wait(), out, err
# 範例
code, out, err = run_cmd('ls -la /tmp')
print(f"exit={code}, out={out}, err={err}")
建議改用 `subprocess.run(..., capture_output=True, text=True)`(Python 3.5+)。
import os SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) # 或 pathlib (Py3.4+) from pathlib import Path SCRIPT_DIR = Path(__file__).resolve().parent
try:
import json
except ImportError:
import simplejson as json # Python 2.5 早期無內建 json
# Python 2.7+
echo '{"hello":1}' | python -m json.tool
# Python 2.6 或無 json 模組
echo '{"hello":1}' | python -m simplejson.tool
// main.c
#include <Python.h>
int main() {
Py_Initialize();
if (!Py_IsInitialized()) { fprintf(stderr, "Python init failed\n"); return -1; }
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");
PyObject* pModule = PyImport_ImportModule("mytest"); // mytest.py
if (!pModule) { PyErr_Print(); return -2; }
PyObject* pFunc = PyObject_GetAttrString(pModule, "test1");
if (!pFunc || !PyCallable_Check(pFunc)) { PyErr_Print(); return -3; }
// 呼叫 test1(int, str)
PyObject* pArgs = Py_BuildValue("(is)", 2, "hello");
PyObject* pResult = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (!pResult) { PyErr_Print(); return -4; }
printf("Result: %ld\n", PyLong_AsLong(pResult));
Py_DECREF(pResult);
Py_Finalize();
return 0;
}
def test1(num, text):
print(f"Python: num={num}, text={text}")
return num * 2
def test2(num):
return f"Result: {num}"
# Python 必須配置 --enable-shared 編譯產生 libpythonX.Y.so ./configure --prefix=/opt/python --enable-shared make && make install # 編譯 C 程式 gcc -I/opt/python/include/python3.11 -L/opt/python/lib -lpython3.11 -Wl,-rpath,/opt/python/lib main.c -o main export LD_LIBRARY_PATH=/opt/python/lib:$LD_LIBRARY_PATH ./main
收藏此表,日常開發遇到對應場景即查即用,效率倍增。