call php function from python

2019-05-06 20:51发布

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?

1条回答
唯我独甜
2楼-- · 2019-05-06 21:32

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)
查看更多
登录 后发表回答