使用 exec() 在 PHP 中运行 python 脚本

Posted

技术标签:

【中文标题】使用 exec() 在 PHP 中运行 python 脚本【英文标题】:Using exec() to run python script in PHP 【发布时间】:2015-04-03 04:20:46 【问题描述】:

我希望用户上传一个文件,然后一个 php 文件检查它是否有效。我的问题是运行 script_template.py ,我使用函数 exec() 在命令行中运行,但它没有返回任何内容,我不明白为什么。提前致谢。我正在使用 xampp。

index.html

<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
            <div id="drop">
                Drop Here

                <a>Browse</a>
                <input type="file" name="upl" multiple />
            </div>

            <input type="submit" value="Upload Image" name="submit">
        </form>

php 文件

$allowed = array('png', 'jpg', 'gif','txt','xlsx','xls');


if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0)


    $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);

    if(!in_array(strtolower($extension), $allowed))
        echo '"status":"error"';
        echo ' <p>The uploaded file extension is incorrect, please try again with the correct file </p>'; 
        exit;
    


 $x=file_validation ( $_FILES['upl']['tmp_name'] )  ;
echo $x;


    if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/'.$_FILES['upl']['name']))
        echo '"status":"success"';
        exit;
    


echo '"status":"error"';
echo 'erro';
exit;



function file_validation($fich) 
    $validation= exec('python script_template.py '.$fich) ;
    echo $validation ;
    

python 文件

#!C:\Python27\python.exe
print "Content-Type: text/html\n"

import sys
fich_input= sys.argv[1]  
print fich_input


def header(fich):
    """
    Extracts the header and it's values from tab separated file
    Requires: fich is tab separated file
    Ensures: dic and aux are dictionaries, where aux associates each header to it's order
    and dic associates each header value to the order number.
    """
    input_fil=open(fich,'r')
    contador_linha=0
    lines =input_fil.readlines()
    dic=
    aux=
    for line in lines:

        contador_linha+=1
        line_words=line.split('\t')
        if contador_linha==1: #header
            aux_counter=1
            header_len=len(line_words)
            for elem in line_words:
                if elem != '\n':
                    aux[aux_counter]=elem
                    aux_counter+=1


        elif contador_linha==2:#create values for keys in header
            aux_counter=1
            for elem2 in line_words:

                if elem2 != '\n':

                    dic[aux_counter]=[elem2]

                    aux_counter+=1

    return (aux,dic)



def header_value(dic1,dic2):
    """
    joins header and it's value
    Requires: dic1 is aux from header(fich) and dic2 is dic from header(fich)
    Ensures: final_dic is a dictionary which associates eache header to value
    """
    final_dic=
    header_len=len(dic1.keys())
    for number in range(1,header_len+1):


        final_dic[dic1[number]]=dic2[number]
    return final_dic



def mol_name(final_dic):
    """
    Finds molecule name for just labelling
    Requires: final_dic is a dictionary returned by header_value
    Ensures: string representing molecule name
    """
    return final_dic['Mol_name'] 

def print_info(final_dic):
    """
    prints in the screen all information contained in the file given by researcher
    Requires: final_dic from header_value
    Ensures: information in the screen
    """
    print str(mol_name(final_dic))
    for key in final_dic:
        print key,':',final_dic[key]

    print '\n'



def general_operation(fich):
    """
    Gathers information required to start database operations and if not give an error
    Requires: fich is a Tab separated file, dic12 is 
    Ensures: Crucial information to database operations
    """
    dics=header(fich)

    header_values= header_value(dics[0],dics[1])

    type_file=''
    if len(header_values) < 21 :
           type_file='no_ref'
    else:
           type_file='ref'


    return (type_file,header_values)


print 'yes'
print general_operation(fich_input)       

python 脚本运行良好,php 忽略它。

【问题讨论】:

你的 Python 脚本所做的只是打印到控制台。我不希望这会给调用它的 PHP 脚本返回任何内容。也许您想写入标准输出? 我最后尝试了 return general_operation(fich_input) 仍然没有发送任何东西。我写了 print 而不是 return 来查看场景中是否出现了任何东西,但没有。 【参考方案1】:

(我假设您使用的是 Windows。)

我认为您需要以不同的方式调用 Python。如果你运行

python http://localhost/bioinformatica/processa_tsv/AJAX_upload/script_template.py

从您计算机上的命令行,它可以工作吗?我猜不是,因为python 的第一个参数应该是本地驱动器上的 Python 文件的名称

尝试运行python C:\path\to\script.py 之类的东西来测试您将在exec() 中输入的命令行。

【讨论】:

$validation= exec('python script_template.py '.$fich) (注意:script_template.py在php文件同一目录下) 你能在命令提示符下试试吗?您可以使用 Windows+R 打开命令提示符,键入“cmd”,然后按 Enter。如果它在命令行中工作,它应该在 PHP 的 exec 中工作。 如果你在exec的结果上调用var_dump,它会显示什么? 这可能是正确的答案;回想一下exec 返回程序输出的最后一行。您可以使用system 输出所有程序输出,或者以更复杂的方式使用exec 将所有输出放在一个字符串中。见php.net/manual/en/function.exec.php。 您需要比“不起作用”更具体。你看到了什么?结果如何?【参考方案2】:

解决了,只需将这部分代码编辑为:

function file_validation($fich) 
 $validation=""
 exec('python script_template.py '.$fich,$validation) ;
    return $validation ;
    

【讨论】:

以上是关于使用 exec() 在 PHP 中运行 python 脚本的主要内容,如果未能解决你的问题,请参考以下文章

如何在 php 中使用 exec 命令运行 codeigniter 控制器功能

如何配置服务器的php,使得能成功运行exec函数?

无法使用 PHP exec 运行 gsutil

如何让exec自己运行,php页面继续运行,让PHP不再阻塞

php的ssh2_exec()函数不能正常使用?

在后台centos服务器中运行php脚本