简体   繁体   中英

Executing Python script from Laravel 4 Controller

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM