Linux 从 PHP 运行 Python 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19735250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:15:02  来源:igfitidea点击:

Running a Python script from PHP

phppythonlinuxexecarchlinux

提问by Abandoned account

I'm trying to run a Python script from PHP using the following command:

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

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

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

However, PHP simply doesn't produce any output. Error reporting is set to E_ALL and display_errors is on.

但是,PHP 根本不产生任何输出。错误报告设置为 E_ALL 并且 display_errors 处于打开状态。

Here's what I've tried:

这是我尝试过的:

  • I used python2, /usr/bin/python2and python2.7instead of /usr/bin/python2.7
  • I also used a relative path instead of an absolute path which didn't change anything either.
  • I tried using the commands exec, shell_exec, system.
  • 我用python2,/usr/bin/python2python2.7不是/usr/bin/python2.7
  • 我还使用了相对路径而不是绝对路径,它也没有改变任何东西。
  • 我尝试使用命令exec, shell_exec, system

However, if I run

但是,如果我跑

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

it works perfectly fine while shutdown nowdoesn't do anything.

它工作得很好,而shutdown now没有做任何事情。

PHP has the permissions to access and execute the file.

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

EDIT: Thanks to Alejandro, I was able to fix the problem. If you have the same problem, don't forget that your webserver probably/hopefully doesn't run as root. Try logging in as your webserver's user or a user with similar permissions and try to run the commands yourself.

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

采纳答案by Alejandro Quiroz

Tested on Ubuntu Server 10.04. I hope it helps you also on Arch Linux.

在 Ubuntu Server 10.04 上测试。我希望它也能帮助你在 Arch Linux 上。

In PHP use shell_exec function:

在 PHP 中使用 shell_exec 函数

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.

通过 shell 执行命令并以字符串形式返回完整的输出。

如果发生错误或命令不产生输出,则返回已执行命令的输出或 NULL。

<?php 

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

?>

In Python file test.py, verify this text in first line: (see shebang explain):

在 Python 文件中test.py,在第一行验证此文本:(参见 shebang 解释)

#!/usr/bin/env python

Also Python file must have correct privileges(execution for user www-data / apache if PHP script runs in browser or curl) and/or must be "executable". Also all commands into .pyfile must have correct privileges:

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

Taken from php manual:

采取从PHP手册

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.

只是对那些试图在 unix 类型平台上使用 shell_exec 并且似乎无法让它工作的人的快速提醒。PHP 作为系统上的 Web 用户执行(对于 Apache 通常为 www),因此您需要确保 Web 用户对您尝试在 shell_exec 命令中使用的任何文件或目录具有权限。否则,它似乎不会做任何事情。

To make executable a file on unix-type platforms:

在 unix 类型平台上制作可执行文件

chmod +x myscript.py

回答by Niklas Lindblad

I recommend using passthruand handling the output buffer directly:

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

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

回答by Colin Miles

Alejandro nailed it, adding clarification to the exception (Ubuntu or Debian) - I don't have the rep to add to the answer itself:

亚历杭德罗(Alejandro)指出了这一点,对异常(Ubuntu 或 Debian)进行了澄清-我没有代表可以添加到答案本身:

sudoers file: sudo visudo

sudoers 文件: sudo visudo

exception added: www-data ALL=(ALL) NOPASSWD: ALL

例外补充: www-data ALL=(ALL) NOPASSWD: ALL

回答by kqw

If you want to know the return status of the command and get the entire stdoutoutput you canactually use exec:

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

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

$outis an array of all lines. $statusis the return status. Very useful for debugging.

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

If you also want to see the stderroutput you can either play with proc_openor simply add 2>&1to your $command. The latter is often sufficient to get things working and way faster to "implement".

如果您还想查看stderr输出,您可以使用proc_open或简单地添加2>&1到您的$command. 后者通常足以让事情工作并且更快地“实施”。

回答by Tim Hallman

In my case I needed to create a new folder in the wwwdirectory called scripts. Within scriptsI added a new file called test.py.

就我而言,我需要在www名为scripts. 在里面scripts我添加了一个名为test.py.

I then used sudo chown www-data:root scriptsand sudo chown www-data:root test.py.

然后我使用sudo chown www-data:root scriptssudo chown www-data:root test.py

Then I went to the new scriptsdirectory and used sudo chmod +x test.py.

然后我转到新scripts目录并使用sudo chmod +x test.py.

My test.py file it looks like this. Note the different Python version:

我的 test.py 文件看起来像这样。注意不同的 Python 版本:

#!/usr/bin/env python3.5
print("Hello World!")

From php I now do this:

从 php 我现在这样做:

$message = exec("/var/www/scripts/test.py 2>&1");
print_r($message);

And you should see: Hello World!

你应该看到:Hello World!

回答by Gerald Joshua

This is so trivial, but just wanted to help anyone who already followed along Alejandro's suggestion but encountered this error:

这太微不足道了,但只是想帮助已经遵循亚历杭德罗建议但遇到此错误的任何人:

sh: blabla.py: command not found

sh:blabla.py:找不到命令

If anyone encountered that error, then a little change needs to be made to the php file by Alejandro:

如果有人遇到该错误,那么 Alejandro 需要对 php 文件进行一些更改:

$command = escapeshellcmd('python blabla.py');

回答by SMshrimant

The above methods seem to be complex. Use my method as a reference.

上面的方法看起来很复杂。使用我的方法作为参考。

I have these two files:

我有这两个文件:

  • run.php

  • mkdir.py

  • 运行.php

  • 目录

Here, I've created an HTML page which contains a GObutton. Whenever you press this button a new folder will be created in directory whose path you have mentioned.

在这里,我创建了一个包含GO按钮的 HTML 页面。每当您按下此按钮时,都会在您提到的路径的目录中创建一个新文件夹。

run.php

运行.php

<html>
 <body>
  <head>
   <title>
     run
   </title>
  </head>

   <form method="post">

    <input type="submit" value="GO" name="GO">
   </form>
 </body>
</html>

<?php
 if(isset($_POST['GO']))
 {
  shell_exec("python /var/www/html/lab/mkdir.py");
  echo"success";
 }
?>

mkdir.py

目录

#!/usr/bin/env python    
import os    
os.makedirs("thisfolder");

回答by Agnel Vishal

To clarify which command to use based on the situation

根据情况明确使用哪个命令

exec()- Execute an external program

exec()- 执行外部程序

system()- Execute an external program and display the output

system()- 执行外部程序并显示输出

passthru()- Execute an external program and display raw output

passthru()- 执行外部程序并显示原始输出

Source: http://php.net/manual/en/function.exec.php

来源:http: //php.net/manual/en/function.exec.php