問題描述
我有一個 WordPress 安裝個人部落格,我正在逐漸移植所有的小網站,我多年來寫的部落格上的頁面。
一個這樣的頁面是 http://www.projecttoomanycooks.co.uk/cgi-bin/memory/majorAnalysis.py,它是一個簡單的 python 指令碼,返回一個單詞列表 – 我想在 wordpress 頁面中嵌入這個行為 – 有人可以指出我正確的方向,以便輕鬆地執行一個 python 的位置 WordPress 的?
編輯 – 遵循下面的美妙答案,我有更多的東西… 但不幸的是仍然不太在那裡
我有在伺服器上執行的 python …
projecttoomanycooks server [~/public_html/joereddington/wp-content/plugins]#./hello.py
Hello World!
它與啟用的外掛在同一個目錄中…
python 程式碼… 有以下程式碼…
#!/usr/bin/python
print("Hello World!")
php:
<?php
/**
* Plugin Name: Joe's python thing.
* Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
* Description: A brief description of the Plugin.
* Version: The Plugin's Version Number, e.g.: 1.0
* Author: Name Of The Plugin Author
* Author URI: http://URI_Of_The_Plugin_Author
* License: A "Slug" license name e.g. GPL2
*/
/*from http://wordpress.stackexchange.com/questions/120259/running-a-python-scri
pt-within-wordpress/120261?noredirect=1#120261 */
add_shortcode( 'python', 'embed_python' );
function embed_python( $attributes )
{
$data = shortcode_atts(
array(
'file' => 'hello.py'
),
$attributes
);
$handle = popen( __DIR__ . '/' . $data['file'], 'r');
$read = fread($handle, 2096);
pclose($handle);
return $read;
}
最佳解決方案
您可以使用 popen()讀取或寫入 Python 指令碼 (這與任何其他語言一起使用) 。如果需要互動 (傳遞變數),請使用 proc_open()。
一個簡單的例子列印 Hello World!在 WordPress 外掛
建立外掛,註冊一個短碼:
<?php # -*- coding: utf-8 -*-
/* Plugin Name: Python embedded */
add_shortcode( 'python', 'embed_python' );
function embed_python( $attributes )
{
$data = shortcode_atts(
[
'file' => 'hello.py'
],
$attributes
);
$handle = popen( __DIR__ . '/' . $data['file'], 'r' );
$read = '';
while ( ! feof( $handle ) )
{
$read .= fread( $handle, 2096 );
}
pclose( $handle );
return $read;
}
現在,您可以使用 [python]或 [python file="filename.py"]的帖子編輯器中使用該短碼。
將要使用的 Python 指令碼放在與外掛檔案相同的目錄中。您也可以將它們放入目錄並調整短碼處理程序中的路徑。
現在建立一個複雜的 Python 指令碼,如下所示:
print("Hello World!")
就這樣。使用短碼,並得到這個輸出:
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。
