1

I'm trying to execute a Python script from my Controller. In my controllers directory I created a folder called pythonScripts in which I have placed my script. From my controller function I am getting data from the database, in json format, and passing it to python to create a network and then do some analysis on the network using networkx. The problem is that i'm unable to execute the script. The following is my code for runing the script.

$output = array();
exec("/pythonScripts/createNetwork.py '{$connections}' ", $output);
return json_encode($output);

Where $connections is JSON data about a users connections with other users.

In the python script, at the moment, I'm only printing out whatever is passed in to see if the script is being executed but in return I get an empty array []. The following is my python script.

import json
import networkx as nx 
import sys
from networkx.readwrite import json_graph


def main():
    userJSONData = sys.argv[1] #the JSON format of user data will be passed into this script.
    print userJSONData


if __name__ == '__main__':
    main()

I can't tell if the script is executing ... any help?

1
  • unrelated: to parse json data: data = json.loads(sys.argv[1]) Commented May 5, 2014 at 10:25

1 Answer 1

3

You must get the return value from your script execution to check if it was successful (== 0) and if your script is not executable, you must also call python:

exec("/usr/bin/python /pythonScripts/createNetwork.py '{$connections}'", $output, $return);

if ($return) {
    throw new \Exception("Error executing command - error code: $return");
}

var_dump($output);
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, I get the following in firebug. "type":"Exception","message":"Error executing command - error code: 127
And now my exec() looks the same as yours. exec("python /pythonScripts/createNetwork.py '{$connections}' ", $output, $return);
So apparently code 127 means command not found ... why is it giving this??
Thanks @Antonio, for the answer. It wasn't the python path that I had to tell the script, apparently I had to specify the exact path of the script. It works now. Thanks again.
You can keep it "relative" by using app_path().'/controllers/pythonScript/script.py'
|

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.