php - 从 Laravel 4 Controller 执行 Python 脚本

标签 php python json laravel laravel-4

我正在尝试从我的 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/

相关文章:

ios - 如何在ios swift中将对象数组转换为Json数组或Json字符串?

json - POST 时出现 404 错误。 Angular .js

php - 无法在centos 7中使用php连接postgres数据库

php - 从cmd运行脚本时如何设置文件的包含路径

php - 如何通过 Telegram 机器人发送自定义表情符号?

php - 如何在mysql数据库中插入多行

python - 有条件地合并列表

python - tkinter (python) 中的 IPAD-X/Y 和 PAD-X/Y 是否不同?

python - 如何: fit_generator in keras

php - 从 php 检索 JSON 时出错 - Android