Brian Cox
Brian Cox

Reputation: 75

PHP calling Python, returning multiple values

I'm setting up a SOAP server using php. In processing the SOAP requests, I will then need to call some existing python scripts. These scripts have typically returned 3 values: success, description, and data.

How do I pass all three values back to the php?

My request is:

exec('python test.py', $output);

test.py does:

from getData import getData

status, description, data = getData()

return status, description, data

and my existing python looks something like this:

def getData():
    database = Database()

    # get all the Data from the db
    data = database.getData()

    if data is None:
        return False, "...notes...", ""

    return True, "...notes...", data

I'm not sure the return in test.py is correct. But even if it is, when I look at var_dump($output) all I see is "Array"

Anyone have any ideas?

TIA,

Brian

Upvotes: 3

Views: 6783

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270637

Since the exec() call receives shell output into the variable $output, it has no way of receiving the returned strings from the Python functions. Instead of returning them, you must print them, and each printed line will go into the exec() array $output.

The main script must print the values to stdout:

from getData import getData
status, description, data = getData()

# Print the values
print("STATUS:", status)
print("DESCRIPTION:", description)
print("DATA:", data)

In PHP, examine the output you get back:

exec("python test.py", $output);
var_dump($output);

You will need to format your print statements in Python into something you can easily parse values from in PHP, such as one thing per line, or key: value pairs that you can explode().

Upvotes: 5

Related Questions