简体   繁体   中英

Run python script inside php

I am trying to run a python script in php to test file reading so i can continue my work and do more code. I tried with a small txt file and php file but the output of python script is an empty string. All the files are in the same directory and i am using XAMPP in VISTA OS.

php file

<?php

$validation= exec('python script.py juliodantas.txt') ;
echo $validation ;

var_dump($validation);

?>

python file: (script.py)

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

import sys
fich_input= sys.argv[1]

def test(fich):
    input_fil=open(fich,'r')
    s=''
    cont=0
    for line in input_fil:
        cont+=1
        s+=line
    return (line,cont)

test(fich_input)

txt file is tab formated file (juliodantas.txt)

CAS Smiles InchI Mol_name LAB Institution Species Cell_type Subcellular Bio_target Conditions Asay_parameter Observations Assay_ID strain Tissue target_type value Unity Comparisons Experimental_error
12233 535 2435d 3r5rg 4t4t 4t 4t34t4 4t4t4 4trgdf vgery4 345y4 grfbg gergh hj6yu wde kukl derj,.i gjyy htht5u thyt5 tht56 thtrj4yeg

the output of php:

string(0) ""

If I may quote the manual for exec() :

The last line from the result of the command.

Your Python program prints out "Content-Type: text/html\\n" , so the last line of its output is an empty line.

If you want the whole output of the program inside a variable, use the second, optional parameter of exec :

$validation = "";
exec('python script.py juliodantas.txt', $validation);

echo impode("\n", $validation); // should print "Content-Type: text/html\n"

Update:

I've previously used the deprecated (and apparently, now removed) call-with-pass-by-reference syntax. Shame on me. Also, apparently exec() returns the output as a line-based array, so you've got to join it if you want to have it as a single string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM