如何在Python中包含PHP脚本? [英] How do I include a PHP script in Python?

查看:80
本文介绍了如何在Python中包含PHP脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP脚本(news-generator.php),当包含它时,它会抓取一堆新闻并将其打印出来.现在,我正在将Python用于我的网站(CGI).当我使用PHP时,在新闻"页面上使用了类似的方法:

I have a PHP script (news-generator.php) which, when I include it, grabs a bunch of news items and prints them. Right now, I'm using Python for my website (CGI). When I was using PHP, I used something like this on the "News" page:

<?php
print("<h1>News and Updates</h1>");
include("news-generator.php");
print("</body>");
?>

(为简单起见,我将示例简化了.)

(I cut down the example for simplicity.)

有没有一种方法可以让Python执行脚本(news-generator.php)并返回可以跨平台工作的输出?这样,我可以做到这一点:

Is there a way I could make Python execute the script (news-generator.php) and return the output which would work cross-platform? That way, I could do this:

page_html = "<h1>News and Updates</h1>"
news_script_output = php("news-generator.php") //should return a string
print page_html + news_script_output

推荐答案

import subprocess

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

# YOUR CODE BELOW:
page_html = "<h1>News and Updates</h1>"
news_script_output = php("news-generator.php") 
print page_html + news_script_output

这篇关于如何在Python中包含PHP脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆