从PHP调用Python脚本时出现问题

这是我的python脚本,它在执行时会创建一个“test.txt”文件。 当我执行使用终端(Ubuntu 11.04) root@gml-VirtualBox:/var/www/HMS# python test.py 它按照我的预期在/var/www/HMS目录中创建“test.txt”。

test.py:

#!/usr/bin/env python

def init():
    filename = "test.txt"
    file = open(filename, 'w')
    file.write("This is the new content of test.txt :-)")
    file.close()
    print "done"

def main():
    init()

if __name__ == '__main__':
    main()

但是当我尝试使用PHP调用此test.py时,它不会创建'test.txt'输出文件。

index.php:

$tmp = exec("python test.py");
echo "temp: $tmp";

test.pyindex.php都在同一个目录下( /var/www/HMS/ )。 但是当我像这样修改test.py

#!/usr/bin/env python

def init():
    print "done"

def main():
    init()

if __name__ == '__main__':
    main()

它打印temp: done在浏览器中temp: done ,这是我的预期。

我不知道为什么我以前的Python代码没有按预期工作。


当你在命令行上测试python脚本时,你以root身份运行。 有可能你没有以root身份运行web服务器(这是件好事),并且web服务器的用户没有适当的权限来创建和/或写入该文件。

链接地址: http://www.djcxy.com/p/9297.html

上一篇: Problem in calling Python script from PHP

下一篇: What is the purpose of self?