2017-10-21 127 views
0

我很難在python中解析數組時來自php文件。從PHP發送數組到Python,然後在Python中解析

test.php的

$count = 3; 
    $before_json = array("qwe","wer","ert"); 
    print_r($before_json); 

    $after_json = json_encode($before_json); 
    echo $after_json; 

    $command = escapeshellcmd("test.py $after_json $count"); 
    $output = shell_exec($command); 
    echo $output; 

的print_r($ before_json);將顯示 - Array([0] => qwe [1] => wer [2] => ert)

echo $ after_json;將顯示 - [ 「QWE」, 「WER」, 「ERT」]

py.test

import sys 
    after_json = sys.argv[1] 
    count = sys.argv[2] 
    print (device_id) 

打印(after_json)將打印 - [QWE,疫情週報,ERT]

打印( after_json [1])將打印 - q

如何打印出after_json中的任何3個項目?

+3

你忘了解析Python中的json。導入'json'模塊,然後您可以使用'json.loads(after_json)'將JSON字符串轉換爲列表。 **更新**:我覺得這應該是一個答案,而不是一個評論,但我會留下評論,因爲它已經有一些upvotes。 – rickdenhaan

+0

首先讓python程序執行你期望的操作 - 你只是讀取一個字符串並從字符串中輸出第一個字符......並嘗試使用臨時文件或管道在程序之間發送數據,而不是命令行 – MatsLindh

回答

0

你仍然需要解析Python中的JSON字符串。您可以使用json模塊爲:

import sys, json 
after_json = sys.argv[1] 
count = sys.argv[2] 

parsed_data = json.loads(after_json) 
print (parsed_data[0]) # will print "qwe" 
0

你所看到的問題是缺乏在Python JSON解析,如經rickdenhaan說。

但是你也需要確保正確引用您的字符串,當你在這條線將其發送到shell解釋:

$command = escapeshellcmd("test.py $after_json $count"); 

如果我們手工填寫的變量,我們會得到下面的結果(不知道什麼是$count,所以我只是假設值爲3):

$command = escapeshellcmd("test.py [\"qwe\",\"wer\",\"ert\"] 3"); 

這隻適用,因爲在你的JSON格式沒有空格。只要分析過的JSON中有空格,Python腳本的shell調用就會完全失敗。這也是一個安全噩夢,因爲JSON數組的每個元素都可能導致shell中的任意代碼執行。

當你將它們傳遞給shell時,你必須逃避你的論點。爲此,您應該使用功能escapeshellarg

這可能是你想做的事,而不是什麼:

$escaped_json = escapeshellarg($after_json) 
$command = escapeshellcmd("test.py $escaped_json $count"); 

如果你不是100%肯定$count是一個整數,你也應該調用escapeshellarg上的參數。

+0

謝謝大家。我做了你的改變,但我得到一個空白輸出。 $ count只是一個計數器,我將在py腳本中循環使用。測試。php是 $ count = 3; $ before_json = array(「qwe」,「wer」,「ert」); $ after_json = json_encode($ before_json); $ escaped_json = escapeshellarg($ after_json); \t $ command = escapeshellcmd(「python test.py $ escaped_json $ count」); $ output = shell_exec($ command); echo $ output; 和test.py是 進口SYS,JSON escaped_json = sys.argv中[1] 計數= sys.argv中[2] parsed_data = json.loads(escaped_json) 打印(parsed_data [0]) – Gino

+0

也注意到在執行parsed_data = json.loads(escaped_json)之後做一個簡單的打印「測試」將不會打印 – Gino

+0

如果我打印帶有test.py的escaped_json,我得到這個\ [\「qwe \」,\「wer \ 「,\」ert \「\] – Gino