5

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?

2 Answers 2

12

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)

Note that for Python3 you need res = php(code.encode()), see the answer below

8
  • How do i access start function from python script?
    – ishita
    Nov 26, 2013 at 12:44
  • I updated my code. You should be able to figure it out from here. Nov 26, 2013 at 13:22
  • I got error "Could not open input file:". Is there any other way to do that?
    – ishita
    Nov 26, 2013 at 13:50
  • Did you edit the code I gave you to reflect the path to where your file is located? I am not here to do everything for you. Read the code until you understand it and then implement it. Nov 26, 2013 at 13:55
  • 1
    I suggest you study a bit more Python and PHP in order to better understand how they work. This should help you figure out things by yourself much easier. Most people here would not have bothered as much as I did. Nov 29, 2013 at 10:26
2

Small update to previous response:

For python3 code string should be encoded to bytes-like object

php(code.encode())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.