gpt4 book ai didi

php - 从 PHP 运行 Python 脚本

转载 作者:IT老高 更新时间:2023-10-28 11:51:17 26 4
gpt4 key购买 nike

我正在尝试使用以下命令从 PHP 运行 Python 脚本:

exec('/usr/bin/python2.7/srv/http/assets/py/switch.py​​ arg1 arg2');

然而,PHP 根本不产生任何输出。错误报告设置为 E_ALL 并且 display_errors 开启。

这是我尝试过的:

  • 我使用 python2/usr/bin/python2python2.7 而不是 /usr/bin/python2。 7
  • 我还使用了相对路径而不是绝对路径,它也没有改变任何东西。
  • 我尝试使用命令 execshell_execsystem

但是,如果我运行

if (exec('echo TEST') == 'TEST')
{
echo 'exec works!';
}

它工作得很好,而 shutdown now 什么都不做。

PHP 具有访问和执行文件的权限。

编辑:感谢 Alejandro,我能够解决问题。如果您有同样的问题,请不要忘记您的网络服务器可能/希望不会以 root 身份运行。 尝试以您的网络服务器用户或具有类似权限的用户身份登录,然后尝试自己运行命令。

最佳答案

在 Ubuntu Server 10.04 上测试。我希望它对您在 Arch Linux 上也有帮助。

在 PHP use shell_exec function :

Execute command via shell and return the complete output as a string.

It returns the output from the executed command or NULL if an erroroccurred or the command produces no output.

<?php 

$command = escapeshellcmd('/usr/custom/test.py');
$output = shell_exec($command);
echo $output;

?>

进入 Python 文件 test.py,在第一行验证此文本:(see shebang explain) :

#!/usr/bin/env python

If you have several versions of Python installed, /usr/bin/env willensure the interpreter used is the first one on your environment's$PATH. The alternative would be to hardcode something like#!/usr/bin/python; that's ok, but less flexible.

In Unix, an executable file that's meant to be interpreted can indicatewhat interpreter to use by having a #! at the start of the first line,followed by the interpreter (and any flags it may need).

If you're talking about other platforms, of course, this rule does notapply (but that "shebang line" does no harm, and will help if you evercopy that script to a platform with a Unix base, such as Linux,Mac, etc).

This applies when you run it in Unix by making it executable(chmod +x myscript.py) and then running it directly: ./myscript.py,rather than just python myscript.py

make executable a file on unix-type platforms :

chmod +x myscript.py

还有 Python 文件 must have correct privileges (如果 PHP 脚本在浏览器或 curl 中运行,则对用户 www-data/apache 执行)和/或必须是“可执行的”。此外,.py 文件中的所有命令都必须具有正确的权限。

拍摄 from php manual :

Just a quick reminder for those trying to use shell_exec on aunix-type platform and can't seem to get it to work. PHP executes asthe web user on the system (generally www for Apache), so you need tomake sure that the web user has rights to whatever files ordirectories that you are trying to use in the shell_exec command.Other wise, it won't appear to be doing anything.

关于php - 从 PHP 运行 Python 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19735250/

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