gpt4 book ai didi

php - 从 PHP 执行 Python - 选择 Python 版本 (Linux - CentOS)

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:48 25 4
gpt4 key购买 nike

我想从 php 执行 python,我有一个脚本可以很好地用于默认的 python 解释器。我有默认的 python 2.6.6 安装在/usr/bin/python 和 python 2.7.3 安装在/usr/local/bin/python2.7 的 centos。你可以看到默认的 python 版本是什么:

[root@me ~]# python -V
Python 2.6.6

[root@me ~]# python2.7 -V
Python 2.7.3

现在我想从 php 调用一个简单的 python 脚本。它应该在 python 2.7.3 中执行,而不是在 python 2.6.6 中执行。但我只能使用默认版本的 python 做到这一点。

PHP(测试.php):

<?php
ini_set('display_errors', 'on');
$output = array();
$dir = dirname(__FILE__);
$command = "/usr/bin/python ". $dir . "/test.py";
$command1 = "/usr/local/lib/python2.7/ ". $dir . "/test.py";
$output = null;
exec($command, $output);
var_dump($output);
?>

Python(测试.py):

#!/usr/bin/env/python2.7
import sys
print(sys.version)

输出(在浏览器中运行 test.php 后):

array(2) { [0]=> string(41) "2.6.6 (r266:84292, Jan 22 2014, 09:42:36)" [1]=> 
string(38) "[GCC 4.4.7 20120313 (Red Hat 4.4.7-4)]" }

所以当我使用时:

 exec($command, $output);

一切都很好,它显示了正确的 python 版本 (2.6.6)

但是当我运行 test.php 时:

exec($command1, $output);

我得到这些结果(没有结果):

array(0) { }

因此没有结果,所以我想知道python是否看到了所有安装2.7.3

从命令行 2.7.3 可用 - 例如:

[root@me ~]# python2.7
Python 2.7.3 (default, Jan 2 2015, 00:56:13)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "it works"
it works

那我该如何解决呢?

编辑:

The result of whereis -b python :python: 

/usr/bin/python /usr/bin/python2.6 /usr/lib/python2.6 /usr/lib64/python2.6
/usr/local/bin/python2.7-config /usr/local/bin/python2.7 /usr/local/lib/python2.7
/usr/include/python2.6

最佳答案

  1. 您的test.py 文件中有错误。在终端中执行该文件会显示以下输出:

    bash: ./test.py: /usr/bin/env/python2.7: bad interpreter: Not a directory

    要解决此问题,请将第一行设置为:

    #!/usr/bin/env python2.7

    注意envpython2.7之间的空格。

  2. 您通过执行 /usr/bin/python 而不是运行脚本本身来覆盖文件中设置的 Python 解释器。您应该按如下方式执行 Python 脚本:

    ini_set('display_errors', 'on');
    $output = array();
    $command = dirname(__FILE__) . "/test.py";
    exec($command, $output);
    var_dump($output);

    注意:记得在 Python 文件上设置执行位:

    chmod +x test.py

关于php - 从 PHP 执行 Python - 选择 Python 版本 (Linux - CentOS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27743641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com