在 Python 中执行 php 代码

2022-08-30 13:35:25

出于某种原因,我必须运行一个php脚本才能从Python获取图像。因为php脚本非常大,它不是我的,所以我需要几天的时间才能找到使用的正确算法并将其转换为python。

我想知道是否有任何方法可以在python中运行php脚本,参数很少,返回图像。


答案 1

示例代码:

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()

答案 2

你可以简单地从Python执行php可执行文件。

编辑:使用 subprocess.run 的 Python 3.5 及更高版本的示例:

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

推荐