2013-08-26 15 views
1

我正在使用下面的代碼來啓動python腳本並將php變量傳遞給它。我如何將許多PHP變量傳遞給python

$tmp = exec("python path/to/pythonfile.py $myVariable $mySecondVariable", $output); 

這工作得很好,我的問題是我需要將100多個變量傳遞給python腳本。我不希望這個執行線變得非常漫長和難以管理。我還探索通過一個php陣列而不是一個可變的用下面的代碼:

$checked = array(
"key1"  => "1" 
"key2"  => "1" 
"key3"  => "1" 
); 
$checkedJson = json_encode($checked); 
$tmp = exec("python path/to/pythonfile.py $myVariable $checkedJson", $output); 

有了這個,我已經無法的JSON在Python端進行解碼。我已經能夠在python中對數組變量(undecoded)進行基本打印,但它將每個單獨的字符作爲新的數組值。即[0] = k,[1] = e,[2] = y,[3] = 1,等等... 任何幫助,非常感謝。

只是要清楚,我正在尋找比編碼和解碼數組更簡單的方法。有沒有一種方法可以格式化exec行以允許多個變量。

回答

1

將您的PHP變量存儲在臨時文本文件中,然後使用python來讀取該文件。

簡單而有效。


假設腳本是在同一目錄

PHP部分

長版(自包含的腳本 - 跳到下面的短版,如果你只想要的代碼片段)

<?php 

#Establish an array with all parameters you'd like to pass. 
#Either fill it manually or with a loop, ie: 

#Loop below creates 100 dummy variables with this pattern. 
#You'd need to come up with a way yourself to fill a single array to pass 
#$variable1 = '1'; 
#$variable2 = '2'; 
#$variable3 = '3'; 
#.... 
#$variableN = 'N'; 
#...  
for ($i=1; $i<=100; $i++) { 
    ${'variable'.$i} = $i; 
} 

#Create/Open a file and prepare it for writing 
$tempFile = "temp.dat"; 
$fh = fopen($tempFile, 'w') or die("can't open file"); 

#let's say N=100 
for ($i=1; $i<=100; $i++) { 

    #for custom keys 
    $keyname = 'Key'.$i; 

    # using a variable variable here to grab $variable1 ... $variable2 ... $variableN  ... $variable100 
    $phpVariablesToPass[$keyname] = ${'variable'.$i} + 1000; 

} 

#phpVariablesToPass looks like this: 
# [Key1] => 1001 [Key2] => 1002 [Key3] => 1003 [KeyN] = > (1000+N) 


#now write to the file for each value. 
#You could modify the fwrite string to whatever you'd like 
foreach ($phpVariablesToPass as $key=>$value) { 
    fwrite($fh, $value."\n"); 
} 


#close the file 
fclose($fh); 

?> 


或短,假設$ phpVariablesToPass是充滿了你的價值觀的數組:

#Create/Open a file and prepare it for writing 
$tempFile = "temp.dat"; 
$fh = fopen($tempFile, 'w') or die("can't open file"); 
foreach ($phpVariablesToPass as $key=>$value) { 
    fwrite($fh, $value."\n"); 
} 
fclose($fh); 


的Python代碼段來獲取數據

lines = [line.strip() for line in open('temp.dat')] 

變量現在包含您所有的php數據作爲python列表。

+0

感謝您的建議,我會研究它。 –

+0

讓我知道你是否想要如何做到這一點的例子。我使用臨時文件在語言/腳本之間移動了無數大型數據集,這確實是一條路。 – DrewP84

+0

當然會有幫助。 –