Execute php code in Python

后端 未结 5 2062
时光取名叫无心
时光取名叫无心 2020-11-27 16:30

For some reason, I have to run a php script to get an image from Python. Because the php script is very big and it is not mine, it will takes me days to find out the right a

相关标签:
5条回答
  • 2020-11-27 17:03

    You can use php.py. This would allow you to execute php code in python, like in this example (taken from here):

    php = PHP("require '../code/private/common.php';")
    code = """for ($i = 1; $i <= 10; $i++) { echo "$i\n"; }"""
    print php.get_raw(code)
    
    0 讨论(0)
  • 2020-11-27 17:10

    You can simply execute the php executable from Python.

    Edit: example for Python 3.5 and higher using subprocess.run:

    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
    
    0 讨论(0)
  • 2020-11-27 17:12

    Example code:

    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()
    
    0 讨论(0)
  • 2020-11-27 17:14

    Make a wrapper around the PHP script, which:

    • performs the stuff (If I understand well, it's an image creation),
    • then redirects (301 Moved Permanently) to the result image,
    • (also, the image should be purged some day).

    So you can refer to this service (the PHP script) with a simple HTTP request, from anywhere, you can test it with browser, use from Python prg, you need just download the image the usual way.

    Also, if you have a such standalone sub-system, don't feel bad about implement it with different language/technique. It has several advantages, e.g. you can install that service on a different host.

    Recommended reading: Service-Oriented Architecture on Wikipedia.

    0 讨论(0)
  • 2020-11-27 17:20

    If you can run the PHP script locally from the command-line, subprocess.check_output() will let you can PHP and will capture the return value.

    If you are accessing PHP via a socket, then you can use urllib.urlopen() or urllib.urlretrieve() to pull down the resource.

    0 讨论(0)
提交回复
热议问题