What are the possible methods to do this?
When I either open a page or click a button on my PHP website, it runs a python program that returns some data (maybe a string) back to PHP.
It seems people keep saying to use exec or shell exec but I tested this on WAMP, didn't work for me(maybe I did something wrong).
Is there a method I could do something like a API but not to access database but to just run a program?
EDIT: From advice on comments, I was able to get something.
exec('python get.py', $output);
var_dump($output);
using above, I got output.
C:\wamp64\www\ai\get.php:10:
array (size=0)
empty
my python code is just a print statement that says hello world. do I need something for python side?
EDIT TWO: OMFG FINALLLUUYY GOT IT
$cmd = "C:\Users\Jack\AppData\Local\Programs\Python\Python36\python.exe get.py";
exec($cmd, $output);
var_dump($output);
Related
I am running a webserver for my laboratory that basically has a bunch of scripts I wrote in python for processing and analyzing tabular data.
I have a DigitalOcean droplet with a Laravel application deployed on it. When I want to run a script, I have the user upload some data file, and then from the PHP controller run:
shell_exec(python my_script.py arg1 arg2 etc);
The problem is, there are differences in dependencies and libraries between my development environment and 'production' environment. As such, when I try to run the script from the webserver and there is a python error, the object returned by shell_exec is just null. When the PHP blade template tries to parse/get data from this object, I get an error like so:
In this case, 'matchCount' is just a variable stored within a python list like this:
#Label peptides we found experimentally but do not have an in silico match for... as to predict contaminants
output = {
'sequence': protSeq,
'peptides': pepList,
'observablePeptideCount': str(len(pepList)),
'possibleObserved': possibleObserved,
'matchCount': matchCount,
'coverage': matchSumAA/protSeqAALength*100,
'massList': massList,
'tolerances': tolerances,
}
output = json.dumps(output)
The problem is, I understand the python script failed somewhere, but the error log does not give any indication of why or where. Is there some way I can have the webpage output the python error so I can correct it in the production environment?
Is there a better way to be doing all of this? Thank you for any help.
I won't recommend you print things out in production, but if it's a last resort you can try this:
<?php
$output = '';
$result = '';
exec('python my_script.py arg1 arg2 etc 2>&1', $output, $result);
var_dump($output); // all the output is here
var_dump($result); // gives an exit code, might be 1 if it's error
Currently I am executing Python scripts from PHP with:
<?php
$output = shell_exec('python ../cgi-bin/admin_login.py');
echo $output;
?>
Which is working fine. It displays all the data from the print() calls in the script.
But how can I actually return a value to PHP (and not have it display it as output)? Obviously delete that echo call but Python return doesn't seem to do anything.
The Python script is for a login process and handles all the MySQL work for that; I know limited PHP so that is why I am using Python for this.
After running the script, a result will be generated depending on if login was successful..
e.g. LOGGEDIN, EMPTYUSR, EMPTYPW, WRONGPW. All codes for what went wrong (or right) for further acting on by PHP.
e.g. if LOGGEDIN = True when returned, PHP should create a session so the rest of the site knows a user is logged in.
So what I want is a solution of running that Python from PHP and getting those return values back without displaying them on the page.
Any advice much appreciated,
Ilmiont
Don't use shell_exec(), use exec() instead, then decide what to do depending of returned code.
<?php
exec('python ../cgi-bin/admin_login.py', $output, $code);
switch($code) {
case 0:
echo $output;
break;
// other case may follow
}
?>
WARNING exec() only capture stdout, not stderr.
If you need to get full output use :
exec('python ../cgi-bin/admin_login.py 2>&1', $output, $code);
I want to read the console logs of a process that is running, I currently have this
$output = shell_exec('pgrep tfs');
echo "<pre>$output</pre>";
And that returns me a random number like 34034
I've almost never worked with linux before so I dont really know how to do this.
You do realize that that's what pgrep does, right? It returns the process ID of the process you're asking about. So that's not a random number you're getting back. Your script is working perfectly.
Why don't you find the actual log file itself (usually in /var/logs) and use something like fopen to open and parse it?
I am new to using php and python but I have a task that I am trying to complete and the test code I have does not seem to work. Basically I am trying to get data from an html form (using php) to a python script for processing. After looking at some really useful stuff from other posts I have decided to use pipes. To test the process I have used the following code.
php code:
<?php
$pipe = fopen('Testpipe','r+');
fwrite($pipe, 'Test');
fclose($pipe);
?>
Python code:
#!/usr/bin/env python
import os
pipeName = 'Testpipe'
try:
os.unlink(pipeName)
except:
pass
os.mkfifo(pipeName)
pipe = open(pipeName, 'r')
while True:
data = pipe.readline()
if data != '':
print repr(data)
When I run the Python code I can see the pipe being created in the directory using ls -l but when I use my browser to run the php script (I am running a webserver on a raspberry pi) nothing happens. It has got me a little confused as most of the posts I read state how simple pipes are to get going. I assume on opening the browser (php script through the server) I should see the text come up in the python shell?
Any help would be appreciated.
Ok further to my original post I have modified my original code thanks to alot of trawling through the net and some really useful Python tutorials. I now have something that proves the principal of pipes although I still have to resolve the php side of things but I feel as though I'm getting there now. Revised code is below:
import os,sys
pipe_name = 'testpipe'
def child():
pipeout = os.open(pipe_name, os.O_WRONLY)
while True:
time.sleep(1)
os.write(pipeout, 'Test\n')
def parent():
pipein = open(pipe_name, 'r')
while True:
line = pipein.readline()[:-1]
print 'Parent %d got "%s"' %(os.getpid(),line)
if not os.path.exists(pipe_name):
os.mkfifo(pipe_name)
pid = os.fork()
if pid != 0:
parent()
else:
child()
This has got me on the path to where I want to go so hopefully it may be of use to someone having similar questions.
try to provide an absolute path ("/tmp/TestPipe") to be sure that both are looking to the same file.
Here's the issue:
I am using R to run some statistical analysis. The results of which will eventually be sent to a an embedded swf on the user's client machine.
To do this, I have PHP execute a shell script to run the R program, and I want to retrieve the results of that program so I can parse them in PHP and respond with the appropriate data.
So, it's simply:
$output = shell_exec("R CMD BATCH /home/bitnami/r_script.R");
echo $output;
But, I receive nothing of course, because R CMD BATCH writes to a file. I've tried redirecting the output in a manner similar to this question which changes my script to
$output = shell_exec('R CMD BATCH /home/bitnami/raschPL.R /dev/tty');
echo $output;
But what I get on the console is a huge spillout of the source code, and nothing is echoed.
I've also tried this question's solution in my R script.
tl;dr; I need to retrieve the results of an R script in PHP.
Cheers!
If it writes to file perhaps you could use file_get_contents to read it?
http://php.net/manual/en/function.file-get-contents.php
Found it, the answer is through Rscript. Rscript should be included in the latest install of R.
Using my code as an example, I would enter this at the very top of r_script.R
#!/usr/bin/Rscript --options-you-need
This should be the path to your Rscript executable. This can be found easily by typing
which Rscript
in the terminal. Where I have --options-you-need, place the options you would normally have when doing the CMD BATCH, such as --slave to remove extraneous output.
You should now be able to run your script like so:
./r_script.R arg1 arg2
Important! If you get the error
Error in `contrasts<-`(`*tmp*`, value = "contr.treatment") :
could not find function "is"
You need to include the "methods" package, like so:
require("methods");
Perhaps,a much simpler workaround, would be:
$output = shell_exec('R CMD BATCH /home/bitnami/raschPL.R > /dev/tty 2>&1');
echo $output;
Redirects both STDOUT and STDERR, since R outputs to STDERR, by default.