如何从Python运行php代码字符串?

时间:2019-03-10 00:07:59

标签: php python

我发现您可以使用以下命令从Python运行php文件:

import subprocess

proc = subprocess.Popen('php.exe input.php', shell=True, stdout=subprocess.PIPE)
response = proc.stdout.read().decode("utf-8")
print(response)

但是有没有办法从字符串而不是文件运行php代码?例如:

<?php
  $a = ['a', 'b', 'c'][0];
  echo($a);
?>

2 个答案:

答案 0 :(得分:1)

[编辑]

php -r "code" subprocess.Popen 一起使用:

def php(code):
    p = subprocess.Popen(["php", "-r", code],
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out = p.communicate() #returns a tuple (stdoutdata, stderrdata)
    if out[1] != b'': raise Exception(out[1].decode('UTF-8'))
    return out[0].decode('UTF-8')

code = """ \
  $a = ['a', 'b', 'c'][2]; \
  echo($a);"""
print(php(code))

[原始答案]

我发现了一个simple class,可以让您这样做。
该代码是不言自明的。该类包含3种方法:

  
      
  • get_raw(self,code):给定一个代码块,调用该代码并将原始结果作为字符串返回
  •   
  • get(self,code):给定一个发出json的代码块,调用该代码并将结果解释为Python值。
  •   
  • get_one(自己,代码):给定一个代码块,该代码块发出多个json值(每行一个),产生下一个值。
  •   

您编写的示例如下所示:

php = PHP()
code = """ \
  $a = ['a', 'b', 'c'][0]; \
  echo($a);"""
print (php.get_raw(code))

您还可以使用PHP(prefix="",postfix"")

在代码中添加前缀和后缀。

PS .:我修改了原始类,因为不建议使用popen2。我还使代码与Python 3兼容。您可以get it here

import json
import subprocess

class PHP:
    """This class provides a stupid simple interface to PHP code."""

    def __init__(self, prefix="", postfix=""):
        """prefix = optional prefix for all code (usually require statements)
        postfix = optional postfix for all code
        Semicolons are not added automatically, so you'll need to make sure to put them in!"""
        self.prefix = prefix
        self.postfix = postfix

    def __submit(self, code):
        code = self.prefix + code + self.postfix
        p = subprocess.Popen(["php","-r",code], shell=True,
                  stdin=subprocess.PIPE, stdout=subprocess.PIPE)
        (child_stdin, child_stdout) = (p.stdin, p.stdout)
        return child_stdout

    def get_raw(self, code):
        """Given a code block, invoke the code and return the raw result as a string."""
        out = self.__submit(code)
        return out.read()

    def get(self, code):
        """Given a code block that emits json, invoke the code and interpret the result as a Python value."""
        out = self.__submit(code)
        return json.loads(out.read())

    def get_one(self, code):
        """Given a code block that emits multiple json values (one per line), yield the next value."""
        out = self.__submit(code)
        for line in out:
            line = line.strip()
            if line:
                yield json.loads(line)

答案 1 :(得分:1)

根据Victor Val的回答,这是我自己的精简版。

import subprocess

def run(code):
    p = subprocess.Popen(['php','-r',code], stdout=subprocess.PIPE)
    return p.stdout.read().decode('utf-8')

code = """ \
  $a = ['a', 'b', 'c'][0]; \
  echo($a);"""
print(run(code))