Running a python file from php does not generate the output file - php

I have a problem running another file from php. I want my php params to be the output of running a python file that calls another file itself.
Here is my php file:
<?php
if (isset($_POST['submit'])) {
$params = solve();
}
function solve() {
exec("python array.py", $output);
return $output;
}
?>
If array.py is simply:
if __name__ == "__main__":
print 1
print 2
print 3
print 4
I will get 1,2,3,4 for my output, but I as soon as I change array.py to the following file that calls os.system, I don't get anything. So the new array.py is:
import os
def main():
os.system("python test.py") #test.py creates tmp.txt with 4 lines w/ values 1,2,3,4
def output():
f = open("tmp.txt", "r")
myReturn = []
currentline = f.readline()
while currentline:
val = currentline[:-1] #Getting rid of '\n'
val = int(val)
myReturn = myReturn + [val]
currentline = f.readline()
f.close()
return myReturn
if __name__ == "__main__":
main()
o = output()
print o[0]
print o[1]
print o[2]
print o[3]
Also if I just run test.py, the output is the file tmp.txt:
1
2
3
4
So now, when I run my php file, the output tmp.txt is not even created in the directory and as a result I don't get any output from my php either.
I am not sure why this is happening because when I just run array.py myself, I get the desired output, and the tmp file is created.
EDIT:
I forgot to include: import os above.

Change exec to:
exec("python array.py 2>&1", $output)
Or check the web server or php error log. This will return the error output from the python script to your php script (not normally what you want in production).

Related

the php code is unable to open the python script

i was trying to open and read a pdf from php using python. but after executing the php code in my browser, its not redirecting to python script.
i want my php code to execute the python script and return the output to
php
php code:
<?php
$command = escapeshellcmd("python filename.py");
$output = shell_exec($command);
echo $output;
?>
python code:
this code will read the pdf from the directory and extracts required data from the pdf and gives the corresponding result as an output to the php code which is printed on the browser
import PyPDF2
import re,time
import sys
start_time =time.time()
# open the pdf file
address="pv3.pdf"
object = PyPDF2.PdfFileReader(address)
#print('hello')
# get number of pages
NumPages = object.getNumPages()
l = list()
# extract text and do the search
for i in range(0, NumPages):
PageObj = object.getPage(i)
Text = PageObj.extractText()
l.append(Text)
#print(len(l))
#print(l[0])
d={}
count=0
for i in range(len(l)):
x = l[i].split('\n')
for j in range(len(x)):
if re.search('[0-9]{8}',x[j]) and (j!=len(x)-1 and re.search('-',x[j+1])==None):
#print(x[j],'in page',i+1,',line no',j+1)
count +=1
str = ''
temp =0
for m in range(j+1,len(x)):
if '~na' not in x[m]:
str+=x[m]
else:
temp = 1
break
if temp==0:
#print('hello')
y=l[i+1].split('\n')
for n in range(len(y)):
if '~' in y[n]:
break
str+=y[n]
# if d[x[j]]==None:
d[x[j]]=str
for x,y in d.items():
print(x,"::::",y,"...,")
print()
#print(l[i])
#print(d)
#print('No of matches are',count)
#print(l[0])
end_time = time.time()
#print('Total time taken :',end_time-start_time)

Python program is not executing from php

I developed a script to extract entities from the given text and script is executing fine.
python code:
from nltk.tag import StanfordNERTagger
from nltk.tokenize import word_tokenize
with open('C:\\pythonScripts\\input.txt', 'r') as f:
sample = f.read()
import nltk
def list_tokens(sampletext):
nltk.internals.config_java("C:\\Program Files\\Java\\jdk1.8.0_131\\bin\\java.exe")
classifier='C:\\Users\\gsrilakshmi.INDIA\\Desktop\\stanford\\stanford-ner-2016-10-31\\classifiers\\english.all.3class.distsim.crf.ser.gz'
jar='C:\\Users\\gsrilakshmi.INDIA\\Desktop\\stanford\\stanford-ner-2016-10-31\\stanford-ner.jar'
st = StanfordNERTagger(classifier,jar,encoding='utf-8')
tokenized_text = word_tokenize(sampletext)
classified_text = st.tag(tokenized_text)
with open('C:\\pythonScripts\\output.txt', 'w') as fp:
fp.write('\n'.join('%s %s' % x for x in classified_text))
return classified_text
tokens = list_tokens(sample)
print(tokens)
While calling the python script from php,the output file is not generated.
php code:
$pyscript = 'C:\\Python\Python36-32\python C:\pythonScripts\sample1.py';
$python = 'C:\Python\Python36-32\python.exe';
$p=exec($pyscript,$fulloutput);
exec("python C:\\pythonScripts\\sample1.py > C:\\pythonScripts\\out.txt");
echo $p;
I got the output: '[Found C:\Program Files\Java\jdk1.8.0_131\bin\java.exe: C:\Program Files\Java\jdk1.8.0_131\bin\java.exe]'
Please help me in solving this issue.
Thanks,
Srilu

How can I pass a text file created by php to my python script for processing?

I have a php code that is writing the user input on the webpage into a text file. I wish to pass the text file into my python script that looks like follows:
PHP Script (getfile.php)
<?php
function writetofile($file, $content, $writeType){
$fo = fopen($file, $writeType);
if($fo){
fwrite($fo,$content);
fclose($fo);
}
}
?>
Python Script (predict.py)
clf=joblib.load('model.pkl')
def run(command):
output = subprocess.check_output(command, shell=True)
return output
row = run('cat '+'/Users/minks/Documents/X-test.txt'+" | wc -l").split()[0]
print("Test row size:")
print(row)
matrix_tmp_test = np.zeros((int(row),col), dtype=np.int64)
print("Test matrix size:")
print(matrix_tmp_test.size)
What I am asking is, after writing to a file : $file in php, how can I then pass this file to replace:
row = run('cat '+'/Users/minks/Documents/X-test.txt'+" | wc -l").split()[0]
where the path gets replace by $file and the processing continues? Also, is it possible to pass $file directly to the python code via command line? I am little confused on how this entire passing and processing can be carried out.
Dow you want something like this?
PHP:
$path = "my.txt";
system("python predict.py $path");
Python:
row = run("cat %s | wc -l" % sys.argv[1]).split()[0]

How can I use PHP call python script return result in realtime?

I used PHP to call python script successfully and got the result . But I have to wait for the end of script running without anything output. It looks not friendly to my customer.
How can I return the script results to the PHP web in realtime ?
For instance ,for code below , I want to the PHP web will show output message in realtime instead of show them together at the end . How can I change my code?
Thank you .
PHP Code:
<?php
$k = $_REQUEST['k'];
if (!empty($k))
{
$k = trim($k);
$a = array();
exec('python ./some.py '.$k, $a);
echo $a[0];
}
?>
Python Code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import sys
def do_some(a):
print 'test1'
time.sleep(30)
print 'test2'
if __name__ == '__main__':
print 'Now the python scritp running'
time.sleep(20)
a = sys.argv[1]
if a:
print 'Now print something'
T = do_some(a)
By specification, exec stop the calling program until the end of the callee. After that, you get back the output in a variable.
If you want to send data as soon as they are produced, you should use popen. It will fork a new process, but will not block the caller. So you can perform other tasks, like looping to read the sub-process output line by line to send it to your client. Something like that:
$handle = popen("python ./some.py ", 'r');
while(!feof($handle)) {
$buffer = fgets($handle);
echo "$buffer<br/>\n";
ob_flush();
}
pclose($handle)

Trying to understand the difference between /dev/stdin and php://stdin

As a simple proof of concept, I tried to share a string between forked processes from node to node or from node to php.
Take this simple php code that should log the output of stdin according to the php docs:
echo 'test' | php -r 'echo trim(fgets(STDIN));'
Working fine, but when I'm spawning the process from nodejs:
spawner.js
var fs = require('fs'); var spawn = require('child_process').spawn;
//dummy stdin file
var stdin = fs.openSync('stdin_file', 'w+');
//write the string
fs.writeSync(stdin, 'test');
spawn('php', ['stdin_test.php'], {
cwd: __dirname,
detached: true,
//to fully detach the process nothing should be piped from or to the parent process
stdio: [stdin, fs.openSync('out.log', 'a'), fs.openSync('err.log', 'a')]
})
stdin_test.php
<?php
error_log('php://stdin');
//this should log 'test' but outputs a newline
error_log(trim(fgets(STDIN)));
$t = fopen('/dev/stdin', 'r');
error_log('/dev/stdin:');
//this is working as expected
error_log(trim(fgets($t)));
Why is php://stdin empty? Is it safe to use /dev/stdin? What is the difference between /dev/stdin and php://stdin anyway?
Note that I have this behavior between 2 node processes too: process.stdin is empty but /dev/stdin has the expected result.
Gist available here
stdin man reference
I tested with the following script ( stdin_test.php ) using:
> echo test | php stdin_test.php
stdin_test.php
<?
echo 'STDIN :' ;
echo trim(fgets(STDIN)) ;
echo PHP_EOL;
$stdin_stream = fopen('php://stdin', 'r');
echo 'php://stdin :';
echo trim(fgets($stdin_stream));
echo PHP_EOL;
fclose($stdin_stream);
$stdin_file = fopen('/dev/stdin', 'r');
echo '/dev/stdin :';
echo trim(fgets($stdin_file));
echo PHP_EOL;
fclose($stdin_file);
I get back :
STDIN :test
php://stdin :
/dev/stdin :
If I then comment out the line:
//echo trim(fgets(STDIN));
I get back:
STDIN :
php://stdin :test
/dev/stdin :
If I comment out both of the first stdin echoes (and the file handler pointers), I get:
STDIN :
php://stdin :
/dev/stdin : test
Looking at documentation on php://input and how it is one-time usable unless (after 5.6) "the request body is saved" which is typical for POST requests but not PUT requests (apparently). This has me thinking that they are called "streams" because you get to walk in them once.
Rewind your stdin stream in JS before spawning PHP, else the file pointer will sit at the end of what you just wrote.

Categories