【问题标题】:Is there a way to return a python variable to php?有没有办法将python变量返回给php?
【发布时间】:2020-08-02 08:42:28
【问题描述】:

所以我正在制作一个搜索引擎来搜索互联网,该引擎由 python 驱动,结果的网页是 php。我需要获取变量(即filelist 列表)并将它们返回给php 脚本。如有错别字请见谅。

<html>
    <head>
        <script src='searchengine.js' type='text/javascript'></script>
    </head>
    <body>
        <?php
        $cmd='python3 searchresult.py'+$_POST["searchquery"];
        $output = shell_exec($cmd);
        echo $output;
        ?>
        
    </body>
 </html>

是php代码。

import sys
from os import listdir, basename
import re

keyword=sys.argv[1]
keyword=str(keyword)
filelist=[]
db='C:\\Users\\monik\\Documents\\searchengine\\db'
filestoparse=listdir(db)
for file in filestoparse:
    with open(file,  'r') as f:
        filecontent=str(f.read)
        result=re.findall(keyword, filecontent)
        if len(result)>=5:
            filelist.append(basename(f.name))

是python代码。

【问题讨论】:

  • shell_exec 应该从 python 脚本中捕获 StdOut。尝试在脚本末尾添加打印语句:print(filelist)
  • 在 PHP 中,您使用 . 而不是 + 连接字符串,因此它可能应该是 $cmd='python3 searchresult.py' . $_POST["searchquery"];。但是,直接在 shell_exec() 中执行用户数据是危险的。始终首先转义数据:php.net/manual/en/function.escapeshellcmd.php。您也没有将数据作为参数传递给您的 python 文件,您实际上是在将搜索添加到 python 文件的文件名中。 .py后面需要有空格。
  • 致 Mike67:我不需要显示输出,我需要将值返回给 php 脚本

标签: python php search-engine


【解决方案1】:

您可以将filestoparse 写入一个 json 文件,然后用 php 读取您的 json 文件。

Python

import json 
#parse files in directory to dictionary 
filestoparsetodict ={'file1':'myfile.cdr', 'file2':'picture.psd'}

# write your dictionary to json file
out_file = open("C:/xampp/htdocs/phpjson/myfile.json", "w") 
json.dump(filestoparsetodict, out_file) 
out_file.close()

PHP

<?php
$filelist = file_get_contents("myfile.json");
// Convert content to array 
$myarray = json_decode($filelist, true);
echo $myarray["file1"]; // print an item from array objects
?>

【讨论】:

  • 旁注: jQuery 只是一个在 JS 中构建的库,所以如果你使用 jQuery,你就是在使用 JS,所以这里的“或”有点误导。另外,不要只是给出一个抽象的答案,你应该展示一些真实的例子来说明你的意思。
  • @Magnus Eriksson,这样更好吗?
猜你喜欢
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
相关资源
最近更新 更多