从python调用php函数

2024-04-25 23:49:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我的PHP代码:

function start($height, $width) {
    # do stuff
    return $image;
}

这里是我的Python代码:

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)

在Python中,我想使用PHP start函数。我不知道如何从Python访问start函数。有人能帮我吗?


Tags: path函数代码outputreturnhtmlpagescript
1条回答
网友
1楼 · 发布于 2024-04-25 23:49:23

我就是这样做的。它就像一个符咒。

# 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

要执行特定文件,请执行以下操作:

width = 100
height = 100

code = """<?php

  include('/path/to/file.php');
  echo start(""" + width + """, """ + height + """);

?>
"""
res = php(code)

相关问题 更多 >