My PHP code:
function start($height, $width) {
    # do stuff
    return $image;
}
Here my Python code:
import subprocess
def php(script_path):
        p = subprocess.Popen(['php', script_path], stdout=subprocess.PIPE)
        result = p.communicate()[0]
            return result
    page_html = "test entry"
    output = php("file.php") 
    print page_html + output
    imageUrl = start(h,w)
In Python I want to use that PHP start function. I don't know how to access start function from Python. Can anyone help me on this?
To run a Python script from PHP, we can use the shell_exec function. $command = escapeshellcmd('/usr/custom/test.py'); $output = shell_exec($command); echo $output; to call escapeshellcmd to escape the command string. Then we call shell_exec to run the $command .
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).
Flask is not compatible with php.
php $command = escapeshellcmd('python test.py'); $output = shell_exec($command); echo $output; ?> Save the above script with the . php extension. Start your webserver and visit your web server domain.
This is how I do it. It works like a charm.
# shell execute PHP
def php(code):
  # open process
  p = Popen(['php'], stdout=PIPE, stdin=PIPE, stderr=STDOUT, close_fds=True)
  # read output
  o = p.communicate(code)[0]
  # kill process
  try:
    os.kill(p.pid, signal.SIGTERM)
  except:
    pass
  # return
  return o
To execute a particular file do this:
width = 100
height = 100
code = """<?php
  include('/path/to/file.php');
  echo start(""" + width + """, """ + height + """);
?>
"""
res = php(code)
                        Small update to previous response:
For python3 code string should be encoded to bytes-like object
php(code.encode())
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With