PHP in python through bash


PHP in python through bash

当我在摆弄Python时,我想写一个有自己的web服务器的应用程序。我目前正在使用这个网站的http服务器:Python Web服务器的编写代码,这是脚本的直接链接

这个脚本可以处理html,但我想添加php到它太。因为我知道在Ubuntu中我可以在终端中运行php命令,所以我想在这个脚本中实现相同的逻辑。

我添加了这些行:

import os
os.system('php '+filepath)
然而,我的计划并没有按计划进行。我的test.php中的" <? echo 'hello world'; ?> "将字符串回显到运行webserver.py的终端,它只将输出消息" 0 "返回到web浏览器。

是否有一种方法来捕获php文件的输出成一个字符串在bash,这样我就可以使python web服务器脚本输出与os.system字符串?

我用的是Ubuntu 11.10

对于这种简单的情况,可以使用commands包中的getoutput

from commands import getoutput
response = getoutput('php myscript.php')

您应该避免使用os.system(),而使用更现代的子进程模块。

你可以特别看看popen. communication ()