【问题标题】:Executing Python program that has parameters and use the result as PHP variable? (CodeIgniter, TextBlob, Python 3.4, PHP 7)执行具有参数的 Python 程序并将结果用作 PHP 变量? (CodeIgniter、TextBlob、Python 3.4、PHP 7)
【发布时间】:2017-05-12 20:28:20
【问题描述】:

我有一个连接到数据库的 PHP 脚本。以下数组背后的想法是将此信息插入到数据库中。类别需要由 ML 算法设置,为此我使用 textblob for Python。我正在使用 codeigniter PHP 框架。

$temp = $this->input->post('issue');
$data = array(
   'priority' => '1',
   'Summary' => $this->input->post('issue'),
   'status' => 'Submitted',
   'category' => exec("python machineLearning.py .$temp"),
   'itemsRequired' => ' ',
   'lastUpdate' => date('Y-m-d G:i:s'),
   'ownerID' => $this->session->userdata('username'),
   'managerID' => 'tech'
);

python 脚本 (machineLearning.py) 在单独调用时可以正常工作。我得到的错误是该类别当前保留为空字符串。我尝试使用以下测试:

exec("python machineLearning.py idCard", $output);
print_r($output);

但结果只是一个空数组:

数组()

python 程序在名为 machineLearning 的函数中包含机器学习,并接受一个名为 issue 的参数。我需要传递的值

$this->input->post('issue')

进入python程序中的machineLearning函数。我是否错误地传递了参数,或者 exec() 函数是否需要正确的程序路径?谢谢大家。

找到解决方案

两个当前参数的组合解决了这个问题,我必须更新文件路径,在 exec() 函数内部,并更新 exec function() 的参数部分,但必须另外使用if 语句建议。谢谢两位的帮助

【问题讨论】:

  • 我强烈建议在 shell 命令中使用之前转义/清理用户输入。现在有人可以发布恶意问题,例如; rm -Rf .
  • @Devon 我听说过这个,但目前正在努力让这成为可能。不过,为了将来参考,我该怎么做?
  • php中有一个函数escapeshellarg,应该会派上用场。

标签: php python codeigniter python-3.x php-7


【解决方案1】:

您需要为您的 python 脚本提供一个“main”,该脚本从命令行读取参数并调用您的函数。比如:

if __name__ == "__main__": 
    YourFunction(sys.argv[1])

Maeby 添加一些调试代码来打印您的参数。 关于可执行文件的路径,如果 PATH 环境在您的 php(您的服务器?)上下文中正确设置,要包含 python 的路径,您不需要完整的 exe 路径。

【讨论】:

    【解决方案2】:

    您可能遇到了错误情况,因此没有从exec 返回有效数据。尝试将2>&1 添加到调用和调试输出中。例如,在本地,我尝试一下,我得到:

    exec("python machineLearning.py idCard 2>&1", $output);
    print_r($output);
    
    
    Array
    (
        [0] => /usr/bin/python: can't open file 'machineLearning.py': [Errno 2] No such file or directory
    )
    

    您可能还想在调用中专门编码文件的绝对路径。这将解决上述“找不到文件”错误。

    exec("python /path/to/machineLearning.py idCard 2>&1", $output);
    

    【讨论】:

    • 返回有点延迟,对此深表歉意,但您能解释一下2>&1 部分吗?我环顾四周有点理解,但不明白为什么有必要?
    • 这叫做重定向。基本上,我让您捕获来自 Python 脚本的所有消息,而不仅仅是 STDOUT。 unix.stackexchange.com/questions/99263/…
    猜你喜欢
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2012-06-11
    • 1970-01-01
    • 2015-12-29
    • 2016-08-17
    • 1970-01-01
    相关资源
    最近更新 更多