我正在尝试从我的 Controller 执行 Python 脚本。在我的 Controller 目录中,我创建了一个名为 pythonScripts 的文件夹,其中放置了我的脚本。从我的 Controller 函数中,我从数据库获取 json 格式的数据,并将其传递给 python 以创建网络,然后使用 networkx 对网络进行一些分析。问题是我无法执行该脚本。以下是我运行脚本的代码。
$output = array();
exec("/pythonScripts/createNetwork.py '{$connections}' ", $output);
return json_encode($output);
其中 $connections
是有关用户与其他用户的连接的 JSON 数据。
在 python 脚本中,目前,我只打印出传入的任何内容以查看脚本是否正在执行,但作为返回,我得到一个空数组 []。以下是我的 python 脚本。
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()
我无法判断脚本是否正在执行......有什么帮助吗?
最佳答案
您必须从脚本执行中获取返回值来检查它是否成功(== 0),如果您的脚本不可执行,则还必须调用 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);
关于php - 从 Laravel 4 Controller 执行 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23462723/