Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute php code in Python

Tags:

python

php

For some reason, I have to run a php script to get an image from Python. Because the php script is very big and it is not mine, it will takes me days to find out the right algorithm used and translate it into python.

I am wonder if there is any way to run php script, with few parameters, which returns a image, in python.

like image 777
jiahao Avatar asked Jan 24 '12 09:01

jiahao


People also ask

How do I run PHP in Python?

If you can run the PHP script locally from the command-line, subprocess. check_output() will let you can PHP and will capture the return value. If you are accessing PHP via a socket, then you can use urllib. urlopen() or urllib.

Can Python run PHP?

Yes it will work, and how risky it is depends on how good your implementation is. This is perfectly acceptable if done correctly. I have successfully integrated PHP and C, when PHP was simply too slow to do certain niche tasks in real time (IIRC, PHP is 7 times slower than its C counterpart).

Can I use PHP in flask?

Flask is not compatible with php.


2 Answers

Example code:

import subprocess  # if the script don't need output. subprocess.call("php /path/to/your/script.php")  # if you want output proc = subprocess.Popen("php /path/to/your/script.php", shell=True, stdout=subprocess.PIPE) script_response = proc.stdout.read() 
like image 190
xdazz Avatar answered Oct 04 '22 04:10

xdazz


You can simply execute the php executable from Python.

Edit: example for Python 3.5 and higher using subprocess.run:

import subprocess  result = subprocess.run(     ['php', 'image.php'],    # program and arguments     stdout=subprocess.PIPE,  # capture stdout     check=True               # raise exception if program fails ) print(result.stdout)         # result.stdout contains a byte-string 
like image 43
Sjoerd Avatar answered Oct 04 '22 04:10

Sjoerd