首頁  >  文章  >  後端開發  >  如何從 PHP 無縫交換資料並執行 Python 腳本?

如何從 PHP 無縫交換資料並執行 Python 腳本?

Susan Sarandon
Susan Sarandon原創
2024-10-21 20:45:03574瀏覽

How to Exchange Data and Execute Python Scripts Seamlessly from PHP?

使用 PHP 執行 Python 腳本和資料交換

在 PHP 中執行 Python 腳本並在它們之間交換資料是可行的。一種方法是使用通用語言格式和 stdin/stdout 進行資料傳輸。

例如,讓我們考慮一個場景,您有一個用於網站資料抓取的 PHP 類別。為了增強其功能,您希望整合專為各種網站設計的 Python 腳本。

為了促進兩種語言之間的資料傳輸,您可以利用以下方法:

PHP:

<code class="php">// Data to send to Python
$data = ['as', 'df', 'gh'];

// Execute Python script with JSON data as argument
$result = shell_exec('python /path/to/myScript.py ' . escapeshellarg(json_encode($data)));

// Decode the result
$resultData = json_decode($result, true);

// This will contain: array('status' => 'Yes!')
var_dump($resultData);</code>

Python :

<code class="python">import sys, json

# Load data sent from PHP
try:
    data = json.loads(sys.argv[1])
except:
    print("ERROR")
    sys.exit(1)

# Generate data to send to PHP
result = {'status': 'Yes!'}

# Send to stdout (to PHP)
print(json.dumps(result))</code>

在此範例中,PHP 將JSON 資料作為shell 參數傳送至Python 腳本。腳本讀取數據,處理數據,並透過 stdout 將結果以 JSON 形式傳回。

此方法可以在 PHP 和 Python 之間安全可靠地傳輸資料。以 JSON 等結構化格式交換資料可確保通訊順暢並消除資料傳輸過程中的潛在問題。

以上是如何從 PHP 無縫交換資料並執行 Python 腳本?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn