使用 exec() 在 PHP 中运行 python 脚本 [英] Using exec() to run python script in PHP

查看:44
本文介绍了使用 exec() 在 PHP 中运行 python 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

index.html

<div id="drop">放在这里<a>浏览</a><input type="file" name="upl" multiple/>

<input type="submit" value="上传图片" name="submit"></表单>

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>上传的文件扩展名不正确,请使用正确的文件重试</p>';出口;}$x=file_validation ( $_FILES['upl']['tmp_name'] ) ;回声 $x;if(move_uploaded_file($_FILES['upl']['tmp_name'],'uploads/'.$_FILES['upl']['name'])){echo '{"status":"success"}';出口;}}echo '{"status":"error"}';回声'错误';出口;功能文件验证($ fich){$validation= exec('python script_template.py '.$fich) ;回声 $validation ;}

python 文件

#!C:\Python27\python.exe打印内容类型:文本/html\n"导入系统fich_input= sys.argv[1]打印 fich_input定义标头(fich):"""从制表符分隔的文件中提取标题及其值要求: fich 是制表符分隔的文件确保:dic 和 aux 是字典,其中 aux 将每个标题与其顺序相关联和 dic 将每个标头值与订单号相关联."""input_fil=open(fich,'r')contador_linha=0行 =input_fil.readlines()dic={}辅助={}对于线中线:contador_linha+=1line_words=line.split('\t')如果 contador_linha==1:#header辅助计数器=1header_len=len(line_words)对于 line_words 中的元素:如果 elem != '\n':aux[aux_counter]=elem辅助计数器+=1elif contador_linha==2:#为标题中的键创建值辅助计数器=1对于 line_words 中的 elem2:如果 elem2 != '\n':dic[aux_counter]=[elem2]辅助计数器+=1返回(辅助,dic)def header_value(dic1,dic2):"""加入标题和它的价值要求:dic1 是来自 header(fich) 的 aux 并且 dic2 是来自 header(fich) 的 dic确保:final_dic 是一个字典,它将每个标头与值相关联"""final_dic={}header_len=len(dic1.keys())对于范围内的数字(1,header_len+1):final_dic[dic1[编号]]=dic2[编号]返回 final_dicdef mol_name(final_dic):"""查找仅用于标记的分子名称要求:final_dic 是 header_value 返回的字典确保:表示分子名称的字符串"""返回 final_dic['Mol_name']def print_info(final_dic):"""在屏幕上打印研究人员提供的文件中包含的所有信息需要:来自 header_value 的 final_dic确保:屏幕中的信息"""打印 str(mol_name(final_dic))对于 final_dic 中的键:打印键,':',final_dic[key]打印'\n'def general_operation(fich):"""收集启动数据库操作所需的信息,如果没有则给出错误要求:fich 是制表符分隔的文件,dic12 是确保:数据库操作的关键信息"""dics=header(fich)header_values= header_value(dics[0],dics[1])类型文件=''如果 len(header_values) <21 :type_file='no_ref'别的:type_file='ref'返回 (type_file,header_values)打印是"打印general_operation(fich_input)

python 脚本运行得很好,php 只是忽略它.

解决方案

解决了,只需要编辑这部分代码即可:

function file_validation($fich) {$validation=""exec('python script_template.py'.$fich,$validation);返回 $validation ;}

I want the user to upload a file and then a php file checks if it is valid or not. My problem is in running the script_template.py , i used the function exec() to run in command line but it does not return something and i don't understand why. Thanks in advance. I am using 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 file

$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 file

#!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)       

The python script is running just fine, php simply ignores it.

解决方案

Solved it, just by editing this part of the code to:

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

这篇关于使用 exec() 在 PHP 中运行 python 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆