萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Python 實用技巧速查:編碼、Shell 執行、路徑、JSON、C 擴展調用、格式化輸出

整理 Python 開發中高頻使用的片段,涵蓋編碼宣告、子進程執行、腳本路徑、JSON 相容匯入、CLI 格式化、C/C++ 擴展調用流程與編譯參數。

1. 檔案編碼宣告(Python 2 相容)

# -*- coding: utf-8 -*-

Python 3 預設 UTF-8,通常可省略。

2. 執行 Shell 指令並捕獲輸出

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+)。

3. 取得當前腳本絕對路徑目錄

import os
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
# 或 pathlib (Py3.4+)
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent

4. JSON 模組相容匯入

try:
    import json
except ImportError:
    import simplejson as json  # Python 2.5 早期無內建 json

5. CLI 格式化 JSON 輸出

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

# Python 2.6 或無 json 模組
echo '{"hello":1}' | python -m simplejson.tool

6. C/C++ 調用 Python 嵌入式 API 流程

// 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;
}

7. Python 被調用模組:`mytest.py`

def test1(num, text):
    print(f"Python: num={num}, text={text}")
    return num * 2

def test2(num):
    return f"Result: {num}"

8. 編譯鏈接命令(假設 Python 安裝於 /opt/python)

# 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

9. 進階:Cython / pybind11 / cffi 替代方案

  • Cython:寫 `.pyx` 編譯為 C 擴展,效能最佳、語法近 Python。
  • pybind11:純 C++11 標頭庫,零依賴綁定 C++ 類/函數到 Python,現代首選。
  • cffi:純 Python 定義 C 介面,支援 PyPy,適合調用現有 C 庫。

收藏此表,日常開發遇到對應場景即查即用,效率倍增。

copyright © 萬盛學電腦網 all rights reserved