1

I'm running two Python scripts from my PHP code. To send the values to the scripts I'm doing:

$output1 = shell_exec('python /path/to/my/script1.py '.$name);
$output1 = explode(',', $output1);

and then I'm doing:

$output2 = shell_exec('python /path/to/my/script2.py '.$output1[0]);
$output2 = explode(',', $output2);

$output1 receives the return from the python script correctly but script2.py is returning me a wrong value. Manually setting that value of $output1[0] directly on script2.py gives me a correct value so the problem is not the script.

I already did a echo var_dump($output1); and it's giving me a correct $output1[0], so the problem is neither the value coming from $output1.

Any clues?

Edit1: the value of $output1[0] is a string with white spaces ("Green Day").

Edit2: seems like it's passing just the word "Green". When I pass a string that has a white space, only the first word is passed. That doesn't make sense since I'm exploding by ',' and when I echo the $output1 it shows me the correct string with the white space included.

1 Answer 1

3

I managed to solve the problem so I'll answer here in case someone has the same problem.

The function shell_exec works like this:

$var = shell_exec('python path/to/your/python/script.py '.$var1.' '.$var2. ...);

The arguments you wanna pass to your python script MUST be separated by a white space, that's how python will interpret the multi variables you are sending.

The string "Green Day" has a white space within it, so it was like sending

$var = shell_exec('python path/to/your/python/script.py Green Day');

So when I'd do sys.argv[1] in Python, it would get only "Green" cause "Day" would be the "second" parameter.

So just loop through your sys.argv in Python and concatenate the strings like this:

string = ''
for word in sys.argv[1:]:
    string += word + ' '
Sign up to request clarification or add additional context in comments.

3 Comments

Have you tried quoting your parameters? "Green Day" (repr: '"Green Day"')
I'm not sending the "raw string", the string is contained in $var1. The solution I give above works well.
if, some times, you want to parse more complex arguments (even arguments having quotes) read this article

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.