Skip to content Skip to sidebar Skip to footer

How Do I Pass Many Php Variables To Python

I am using the following code to initiate a python script and pass a php variable to it. $tmp = exec('python path/to/pythonfile.py $myVariable $mySecondVariable', $output); This w

Solution 1:

Store your PHP variables within a temporary text file then use python to read that file.

Simple and effective.


Assuming Scripts are in the same directory

PHP Portion

long version (self contained script - skip to the short version below if you only want the code snippet)

<?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') ordie("can't open file");

#let's say N=100for ($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 likeforeach ($phpVariablesToPassas$key=>$value) {
    fwrite($fh, $value."\n");
}


#close the file
fclose($fh);

?>

or in short, assuming $phpVariablesToPass is an array filled with your values:

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

Python Snippet to Grab the Data

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

the variable lines now contains all of your php data as a python list.

Post a Comment for "How Do I Pass Many Php Variables To Python"