ggntc
ggntc

Reputation: 57

passing parameters to python script via php

I am trying to pass some parameters to a python script via a php script. Here is the code:

$item=array(
    '--native-libs-dir' => "/home/gdqupqmy/quikklyLib/",
    '--type' => "template0001style1",
    '--data'=> "12345",
    '--join' => "horizontal",
    '--output-file' => "/home/gdqupqmy/quikklyLib/saavr-12345.svg");

echo shell_exec("python quikkly-generate-code.py '$item'");

The python script creates an svg image file.

So far, I have had no luck. Any help would be great. And thanks.

Upvotes: 0

Views: 1205

Answers (2)

miken32
miken32

Reputation: 42713

So obviously you can't drop an array into a string and expect output, but similarly you shouldn't just drop a string into a command either. You need to escape your values to prevent possible problems from arising due to special characters, whitespace etc.

Just run through the array and build a command line string like this:

$item = array(
    '--native-libs-dir' => "/home/gdqupqmy/quikklyLib/",
    '--type' => "template0001style1",
    '--data'=> "12345",
    '--join' => "horizontal",
    '--output-file' => "/home/gdqupqmy/quikklyLib/saavr-12345.svg"
);
$args = "";
foreach ($item as $k=>$v) {
    $args .= " $k " . escapeshellarg($v);
}
$cmd = "/usr/bin/python /full/path/to/quikkly-generate-code.py $args";
$result = exec($cmd, $output, $return);
printf("Command exited with code %d, full output follows: %s", $return, print_r($output,1));

This ensures all values are quoted and escaped. (I've made the assumption that the array keys are fixed values and so are not dangerous, if this is not the case they can be run through escapeshellarg as well.)

Upvotes: 1

Emmett Butler
Emmett Butler

Reputation: 6207

You need to ensure that the argument string you're creating is formatted with spaces separating the keys and values. Including the variable $item in the command string won't do it. Instead, you should use an approach similar to this one to build a string containing your CLI argument names and arguments separated by spaces.

An untested example:

$arguments = "";
foreach ($item as $key => $value) {
    $arguments .= sprintf(" %s %s" , $key , $value);
}
echo shell_exec("python quikkly-generate-code.py $arguments")

Upvotes: 0

Related Questions