dongtanhe4607 2013-03-06 15:43
浏览 148
已采纳

从Python中运行PHP脚本 - 将值从Python传递给PHP

SOLVED: Solution ------------------------------------------------------------------

I would like to execute the function getimagesize() from the PHP standard library in a Python script. The function must be passed an image path from Python.

I know how to run a php script in Python, but I can't figure out how to pass an argument from Python -> PHP and then get the result back into Python.

Here is what I have in the Python Script:

def php_script_runner(script_path):
    p = subprocess.Popen(['php', script_path], stdout=subprocess.PIPE)
    result = p.communicate()[0]
    return result

Here is what I have in the PHP file (I am not sure how to pass an argument to it):

<?php getimagesize() ?>

How would I pass an argument to 'get_image_size.php' and have it return the result in Python for further processing?

I would like to further implement this idea for other custom PHP functions. The main goal of this question is not only to find the size of an image, but to be able to use this for other functions in the future that are php intensive.

The main goal of this is to determine:

  1. How to call a PHP script in Python
  2. How to send an agrument to a PHP script from Python
  3. How to parse the output of the PHP script back into Python
  • 写回答

3条回答 默认 最新

  • dongll0502 2013-03-06 17:58
    关注

    Solved by doing this: Python:

    import subprocess
    import json
    import sys
    import os
    
    def php(script_path, argument):
        p = subprocess.Popen(['php', script_path, argument], stdout=subprocess.PIPE)
        result = p.communicate()[0]
        return result
    
    image_dimensions_json =str(php("get_image_size.php", image_location_relative[1:]))
    dic = json.loads(image_dimensions_json)
    print str(dic["0"]) + "|" + str(dic["1"])
    

    The reason for the [1:] is because for some reason the "/" in the path causes an error. I found removing it fixed the issue.

    PHP:

    <?php
    
    echo(json_encode(getimagesize($argv[1])));
    
    ?>
    

    echo or print_r work. I found it easy to convert the array to JSON, as Python has a json decoder built into the standard library.

    Hope this helps people! I plan on using this conecpt to implement much larger PHP functions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab