从PHP运行Python脚本

2024-04-24 04:46:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用以下命令从PHP运行一个Python脚本:

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

但是,PHP不产生任何输出。“错误报告”设置为“全部显示”,并且“显示错误”处于启用状态。

我试过的是:

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

但是,如果我跑

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

shutdown now什么都不做时,它工作得非常好。

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

编辑:多亏了亚历杭德罗,我才解决了这个问题。如果您有同样的问题,不要忘记您的web服务器可能/希望不会以根用户身份运行。尝试以Web服务器的用户或具有类似权限的用户身份登录,并尝试自己运行命令。


Tags: 用户pytest命令echo服务器脚本权限
3条回答

我建议使用passthru并直接处理输出缓冲区:

ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean(); 

在Ubuntu服务器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 error occurred 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

还有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 a unix-type platform and can't seem to get it to work. PHP executes as the web user on the system (generally www for Apache), so you need to make sure that the web user has rights to whatever files or directories that you are trying to use in the shell_exec command. Other wise, it won't appear to be doing anything.

make executable a file on unix-type platforms

chmod +x myscript.py

如果您想知道命令的返回状态并获得整个stdout输出,那么可以实际使用exec

$command = 'ls';
exec($command, $out, $status);

$out是所有行的数组。$status是返回状态。对调试非常有用。

如果您还想看到stderr输出,可以使用proc_open播放,也可以简单地将2>&1添加到$command中。后者通常足以让事情运转起来,并加快“实现”的速度。

相关问题 更多 >