Python PHP equivalent - php

I have been using PHP for a while now with my Apache2 web server on my raspberry pi. It works great, but I get tired of always having to think "how do I X in PHP" or "what was the function name for this in PHP".
I am under the strong impression that there should be something equivalent in which I can replace the <?php ?> code with python code, but my search results have been confusing at best.
I am essentially looking for something where I can write whatever python code I want in an HTML script and have it interpreted and executed and its output inserted into the page when it is requested.
For example, to make a table of users from a list in python.
<table><tr><td>User list</td></tr>
<?python
import json
library=json.load(open(some_json_file,'r'));
for user in library:
print "<tr><td>"+user+"</td></tr>"
?>
</table>
I'm under the impression that chameleon can do this with its code blocks as described here,(https://chameleon.readthedocs.io/en/latest/reference.html) but as I look deeper, I get the impression it doesn't work like I am thinking it should. This is the impression I have gotten from all of the template engines I have looked at, as well as WSGI
Are there good drop in python alternatives for PHP? Or are there ways to cleanly wrap semi complex python code into my php in way that doesn't involve writing an additional python script that is called by PHP? I've tried exec() with python -c; but this was less than ideal having to escape all the ' and " characters...

update
The below code works just fine, but can become very slow if run multiple times in a script (takes about 0.4 seconds each time on a raspberry pi3). I have written a program in python that runs in the background and handles requests from php, and runs about 15x faster. I'm now maintaining it here on github.
Original Answer
After messing around I was able to come up with something mostly suitable for what I am trying to do. Inside my php I create a function that executes python scripts.
<?php
function py($s){
exec("python -c '$s'",$arr);
foreach($arr as $v){
echo $v."\n";}
}
?>
Then I use php Heredoc(equivalent to python """ , means I don't have to escape every single double quote) to fill the function:
<?php
py(<<<python
print "Hello world<br>"
s="ello world"
for x in s:
print x+"<br>"
python
);
?>
outputs >>>
Hello world
e
l
l
o
w
o
r
l
d
the only real downside I am experiencing at this point is that this method precludes me from using single quotes anywhere in my python script... :(. I'll get over it.
EDIT
I added a few more tweaks to make this even more useful. The new function is below:
<?php
function py($s,$return=false){
$s=str_replace("'","'\''",$s);
$h=<<<head
def cleanup():
for x in globals().keys():
if not x.startswith("_"):
del globals()[x]
import dill
try:
dill.load_session("pyworking.pkl")
except:
pass
head;
$f=<<<foot
import dill
dill.dump_session("pyworking.pkl")
foot;
if ($return==false){
echo shell_exec("python -c '$h$s$f'");
}
else {
return shell_exec("python -c '$h$s$f'");
}
}
?>
this allows you to use single quotes in the script and invoke the py() function multiple times in the same script and your variables and modules will follow you. At the end of the script you just call the clean up (or using php clear the pyworking.pkl file) and wipe the environment clean.
I also put this function in a file and in my pyp.ini I used the auto_prepend_file=my/file/location to automatically include it, so no need to load it before hand.
Overall I am very happy with this method, especially since I can read php variables inside my python script. Passing objects is as simple as:
<?php
$data_en=json_encode($data);
py(<<<p
import json
data=$data_en
#do something with data
p
);
?>
this would be perfect if I could think of a way to assign values to php variables inside the script, but its not a bad workaround if you want a fusion of php and python or just a way to do everything in python without writing a python webserver (which i have also done).

Related

How to pass the string from php to tcl and execute the script

I want to pass the string from my php like
<?php
str1="string to pass"
#not sure about passthru
?>
And my tcl script
set new [exec $str1]#str1 from php
puts $new
Is this Possible? Please let me know I'm stuck with this
The simplest mechanism is to run the Tcl script as a subprocess that runs a receiving script (that you'd probably put in the same directory as your PHP code, or put in some other location) which decodes the arguments it is passed and which does what you require with them.
So, on the PHP side you might do (note the important use of escapeshellarg here! I advise using strings with spaces in as test cases for whether your code is quoting things right):
<?php
$str1 = "Stack Overflow!!!";
$cmd = "tclsh mycode.tcl " . escapeshellarg($str1);
$output = shell_exec($cmd);
echo $output;
echo $output;
?>
On the Tcl side, arguments (after the script name) are put in a list in the global argv variable. The script can pull them out with any number of list operations. Here's one way, with lindex:
set msg [lindex $argv 0]
# do something with the value from the argument
puts "Hello to '$msg' from a Tcl script running inside PHP."
Another way would be to use lassign:
lassign $argv msg
puts "Hello to '$msg' from a Tcl script running inside PHP."
Note however (if you're using Tcl's exec to call subprograms) that Tcl effectively automatically quotes arguments for you. (Indeed it does that literally on Windows for technical reasons.) Tcl doesn't need anything like escapeshellarg because it takes arguments as a sequence of strings, not a single string, and so knows more about what is going on.
The other options for passing values across are by environment variables, by pipeline, by file contents, and by socket. (Or by something more exotic.) The general topic of inter-process communication can get very complex in both languages and there are a great many trade-offs involved; you need to be very sure about what you're trying to do overall to pick an option wisely.
It is possible.
test.php
<?php
$str1="Stackoverflow!!!";
$cmd = "tclsh mycode.tcl $str1";
$output = shell_exec($cmd);
echo $output;
?>
mycode.tcl
set command_line_arg [lindex $argv 0]
puts $command_line_arg

Echo Exec ("python filepath $variables") Not Working

I have a bit of backend code that is executed like so:
python filepath $inputvariable
This code prints out some data. As you can see in the screenshot below, when I run this code through terminal it works flawlessly, outputting the expected value:
CHI 110^*^Integrated Chinese Level 1 Part 1^*^https://www.amazon.com/Integrated-Chinese-Simplified-Characters-Textbook/dp/0887276385/ref=sr_1_1?ie=UTF8&qid=1466983577&sr=8-1&keywords=integrated+chinese^*^47.49
But I run into issues when I try to run the same code through php:
echo exec ("python /Users/USERNAME/Desktop/Exeter_Bookstore_Project/localserver/cont/Scripts/Python/serverside.py $classToSend");
This code returns a null value. At first I assumed that I wasn't passing variables through correctly, but echo $classToSend; yielded the correct variable. Then I tried having the php execute a hello world python script, but this also worked proving that the issue wasn't in my python interpreter. Then I thought that maybe the python script wasn't forwarding data quickly enough, but the helloworld.py still worked even with a time delay of 3 seconds.
Does anyone have any idea of what I might have done wrong, or do you need more information. Any help will be greatly appreciated.

PHP + Python - use PHP to pass string to Python program, and parse output

I have a great Python program on my webserver, which I want to use from inside my PHP web app.
Here's an example of the python command, and output as you would see it in terminal:
>>> print MBSP.parse('I ate pizza with a fork.')
I/PRP/I-NP/O/NP-SBJ-1/O/i
ate/VBD/I-VP/O/VP-1/A1/eat
pizza/NN/I-NP/O/NP-OBJ-1/O/pizza
with/IN/I-PP/B-PNP/O/P1/with
a/DT/I-NP/I-PNP/O/P1/a
fork/NN/I-NP/I-PNP/O/P1/fork ././O/O/O/O/.
You might recognize this as a typical POS tagger.
In any case, I'm confused about how to use a PHP-based web app to send this program a string like "I ate pizza with a fork", and somehow get the response back in a way that can be further parsed in PHP.
The idea is to use PHP to pass this text to the Python program, and then grab the response to be parsed by PHP by selecting certain types of words.
It seems like in PHP the usual suspects are popen() and proc_open(), but popen() is only for sending, or receiving information - not both? Is popen() able to give me access to this output (above) that I'm getting from the Python program? Or is there a better method? What about curl?
Here are all my options in terms of functions in PHP:
http://us.php.net/manual/en/function.proc-open.php
I'm lost on this, so thanks for your wise words of wisdom!
I use exec() for this purpose.
exec($command, $output);
print_r($output);
If you want to get a little heavier / fancier... give your python script an http (or xmlrpc) front end, and call that with a GET/POST. Might not be worth all that machinery though!
You could use popen(), and pass the input to your Python script as a command line argument, then read the output from the file descriptor popen gives you, or proc_open() if you want to interact bi-directionally with the Python script.
Example 1 in the proc_open manual: http://us.php.net/manual/en/function.proc-open.php gives an example of this.
If your Python needs it as stdin, you could try popening a command line:
echo "I ate pizza!"|my_python_progam.py
and just read the output. As usual, do proper input validation before sending it to the command-line.
Something like this would work
$command = '/usr/bin/python2.7 /home/a4337/Desktop/script.py'
$pid = popen('$command',r)
........
........
.........
pclose($pid)

want to run c program from php using exec() function

i'm trying to run one c executable file using php exec().
When c contains a simple program like print hello. I'm using
exec('./print.out')
It's working fine. But when I need to pass a argument to my c program I'm using
exec('./arugment.out -n 1234')
It is not working. Can any body tell me how to pass arugment using exec to c program.
From taking a look at the php documentation, it appears that exec treats arguments a bit oddly. You could try doing
exec("./argument.out '-n 1234'")
to prevent it from mangling them (it normally separates them all on space, which might be what's messing it up).

Options for PHP CLI on windows

I'm working with the PHP CLI on windows at the moment to write some small desktop command-line apps.
I wanted to know if and how it may be possible to:
Clear the screen (cls would be the normal command but exec() won't work with it)
Change the color, change the color of parts of the output (seen this in programs before)
Make the command line horizontally bigger - things quickly get unreadable
Is any of the above possible from inside a PHP script?
On Windows, in the standard CLI prompt, you cannot output in colour (as in the answer by Spudley).
You can change the size of the window as a user by right-clicking the command window's title bar and selecting Properties, then ammending values in the Layout tab. I do not think it is possible to ammend the width of the CLI within PHP.
You can check the width of the CLI window on Windows using the function I wrote here
See the PHP manual page for working with the commandline
To directly answer each of your bullet points:
There is a comment on that page which gives a function that can clear the screen. I'll quote it here for you:
<?php
function clearscreen($out = TRUE) {
$clearscreen = chr(27)."[H".chr(27)."[2J";
if ($out) print $clearscreen;
else return $clearscreen;
}
?>
There's also another comment which explains how to change the colours. Again, I'll quote it:
<?php
echo "\033[31m".$myvar; // red foreground
echo "\033[41m".$myvar; // red background
?>
and to reset:
<?php
echo "\033[0m";
?>
You should read through the rest of that page for a whole load more suggestions on how to manipulate the CLI.
The only part of your question that leave unanswered is the third bullet point. Sadly, I don't believe you'll be able to do this, and I don't think it's possible to horizontally resize the Windows command line window.
Hope that helps.
I created a small backup script with PHP, and from what I can remember, you can print backspace characters to remove content. Not really ideal though.
Just google'd it: http://www.php.net/manual/en/features.commandline.php#77142
As far as the third question goes, I suggest you witch the default command line to Console 2. It is a great replacement that not only lets you use any width you like (as long as it fits your screen), but also supports command history, tabs, and some UI sugar.
The provided code will not work under Windows because PHP under windows does something to the command window. I am not sure what PHP does but I wrote a simple Freebasic program with only two lines:
cls
end
I then compiled it and ran it under a regular command line window. It cleared the screen without any kind of a problem. I then did the following in PHP:
<?php
echo "This is a test\n";
system( "cls.exe" );
exec( "cls.exe" );
passthru( "cls.exe" );
?>
When I ran the program it did nothing more than just the "This is a test" line. Thus, there is some kind of suppression going on with PHP that looks for and stops any kind of escape sequence from occurring. Until this is fixed in PHP - you will never be able to do a cls, nor use curses, ncurses, or any other library. What has to be done is to integrate something like FreeBasic's windowing methods as some kind of a class (or maybe just a C set of routines) that will open a new window via THAT language's methodologies and use them to do the text window. Then all of the escape sequences will work. Until then - they won't.
What I find weird about this is that PHP was originally written in Perl and Perl will do ncurses on Windows without any problems. Perl will also allow all escape sequences to work. So there is just something being done on the Windows compile that is causing this problem.

Categories