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

13

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

Sign up to request clarification or add additional context in comments.

8 Comments

How do i access start function from python script?
I updated my code. You should be able to figure it out from here.
I got error "Could not open input file:". Is there any other way to do that?
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.
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.
|
2

Small update to previous response:

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

php(code.encode())

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.