简体   繁体   English

无法从 php 执行 python 脚本

[英]unable to execute python script from php

I want to execute Python script from PHP file.我想从 PHP 文件执行 Python 脚本。 I am able to execute simple python script like:我能够执行简单的 python 脚本,例如:

print("Hello World") 

but when I want to execute following script, nothing happens但是当我想执行以下脚本时,什么也没有发生

from pydub import AudioSegment
AudioSegment.converter = "/usr/bin/ffmpeg"
sound = AudioSegment.from_file("/var/www/dev.com/public_html/track.mp3")
sound.export("/var/www/dev.com/public_html/test.mp3", format="mp3", bitrate="96k")

and same script works fine when I execute it from terminal.当我从终端执行它时,相同的脚本工作正常。 here is my php script:这是我的 php 脚本:

$output = shell_exec("/usr/bin/python /var/www/dev.com/public_html/index.py");
echo $output;

I have also tried following method but no luck:我也尝试过以下方法,但没有运气:

$output = array();
$output = passthru("/usr/bin/python /var/www/dev.com/public_html/index.py");
print_r($output);

please help me请帮我

PHP's passthru function does not have the elegant method for which you may be searching of passing environment variables. PHP 的passthru函数没有您可能正在搜索传递环境变量的优雅方法。 If you must use passthru , then export your variables directly in the command:如果必须使用passthru ,则直接在命令中导出变量:

passthru("SOMEVAR=$yourVar PATH=$newPATH ... /path/to/executable $arg1 $arg2 ...")

If you are inclined toward shell_exec , you may appreciate putenv for the slightly cleaner interface:如果您倾向于shell_exec ,您可能会欣赏putenv的稍微干净的界面:

putenv("SOMEVAR=$yourVar");
putenv("PATH=$newPATH");
echo shell_exec("/path/to/executable $arg1 $arg2 ...");

If you are open to a more robust (if tedious) approach, consider proc_open :如果您对更强大(如果乏味)的方法持开放态度,请考虑proc_open

$cmd = "/path/to/executable arg1 arg2 ..."

# Files 0, 1, 2 are the standard "stdin", "stdout", and "stderr"; For details
# read the PHP docs on proc_open.  The key here is to give the child process a
# pipe to write to, and from which we will read and handle the "passthru"
# ourselves
$fileDescriptors = array(
    0 => ["pipe", "r"],
    1 => ["pipe", "w"],
    2 => ["pipe", "w"]
);

$cwd = '/tmp';
$env = [
    'PATH' => $newPATH,
    'SOMEVAR' => $someVar,
    ...
];

# "pHandle" = "Process handle".  Note that $pipes is new here, and will be
# given back to us
$pHandle = proc_open($cmd, $fileDescriptors, $pipes, $cwd, $env);

# crucial: did proc_open work?
if ( is_resource( $pHandle ) ) {
    # $pipes is now valid
    $pstdout = $pipes[ 1 ];

    # Hey, whaddya know?  PHP has just what we need...
    fpassthru( $pstdout );

    # Whenever you proc_open, you must also proc_close.  Just don't
    # forget to close any open file handles
    fclose( $pipes[0] );
    fclose( $pipes[1] );
    fclose( $pipes[2] );
    proc_close( $pHandle );
}

Acc to your reply, as you want to execute the python script from PHP根据您的回复,因为您想从 PHP 执行 python 脚本

I was able to execute it using the following code我能够使用以下代码执行它

$command = escapeshellcmd('/var/www/yourscript.py');
$output = shell_exec($command);
echo $output;

Please use the above PHP code with the same python script.请使用上面的 PHP 代码和相同的 python 脚本。 Try to run the python script as a GCI script first to make sure it is working and set the permissions to public directory and script as I mentioned before尝试首先将 python 脚本作为 GCI 脚本运行,以确保它正常工作,并将权限设置为我之前提到的公共目录和脚本

===================old ans============================ ===================老答案============================

From what you asked, I guess this is what you are trying to do is that you are trying to run it as a CGI script like http://localhost/yourscript.py根据您的要求,我想您正在尝试将其作为 CGI 脚本运行,例如http://localhost/yourscript.py

And why are you using PHP to execute python script when you can run it directly as a CGI script?当您可以直接将其作为 CGI 脚本运行时,为什么还要使用 PHP 来执行 Python 脚本?

here is what you need to do to make it work like a web page:下面是你需要做的让它像网页一样工作:

  1. enable python CGI in apache ( or in the web server you are using ).在 apache(或您正在使用的 Web 服务器)中启用 python CGI。
  2. put the script in CGI configured directory将脚本放在 CGI 配置的目录中
  3. add proper code to your script to make it work as a CGI script向您的脚本添加适当的代码以使其作为 CGI 脚本工作
#!/usr/local/bin/python
from pydub import AudioSegment
AudioSegment.converter = "/usr/local/bin/ffmpeg"
sound = AudioSegment.from_file("/var/www/dev.com/public_html/track.mp3")
sound.export("/var/www/dev.com/public_html/test.mp3", format="mp3", bitrate="96k")

print "Content-type: text/html"
print
print ""
print ""
print ""
print "Done/ you can perform some conditions and print useful info here"
print ""
  1. Give permissions to the script and make the public directory writable授予脚本权限并使公共目录可写
  2. Access the script http://localhost/your-path-to-script.py访问脚本http://localhost/your-path-to-script.py

I was able to run this properly.我能够正确运行它。 let me know if that's not your case if you want something else如果您想要别的东西,请告诉我是否不是您的情况

In my case, I did this code.就我而言,我做了这段代码。

<?php
chdir('/home/pythontest') ; // python code dir
$commandline="/usr/bin/python3 test.py parameter" ;
exec($commandline, $output, $error) ;
echo $output ;
?>

If you need to set some environments for python, add environment vars like this.如果您需要为 python 设置一些环境,请像这样添加环境变量。

$commmandline="LANG=en_US.utf8 LC_ALL=en_US.utf8 /usr/bin/python3 ..." ;

and check the httpd log.并检查 httpd 日志。

Check this:检查这个:

The apache user has to be in sudoers file, better you don't give sudo to apache instead give apache (www-data) user right to run your python program apache 用户必须在 sudoers 文件中,最好不要给 sudo 给 apache,而是给 apache (www-data) 用户权限来运行你的 python 程序

put first line in your python script: #!/usr/bin/env python so the script knows which program to open it with..在你的python脚本中放第一行: #!/usr/bin/env python ,这样脚本就知道用哪个程序打开它了。

then,然后,

change group:更改组:

chgrp www-data /path/to/python-script.py

make it executabe:使其可执行:

chmod +x /path/to/python-script.py

then try it:然后尝试一下:

shell_exec("/path/to/python-script.py");

I hope this will work!我希望这会奏效! :) :)

You can also exec ffmpeg directly without python:您也可以不使用 python 直接执行 ffmpeg:

$output = shell_exec("/usr/bin/ffmpeg -i in.mp3 -b:a 96k out.mp3");
echo $output;

ffmpeg docs ffmpeg 文档

Answered in 2022. 2022 年回答。

In php 8.0 and above the following method worked.在 php 8.0 及更高版本中,以下方法有效。 Above answers are very useful but i am compiling few extra steps here.以上答案非常有用,但我在这里编译了一些额外的步骤。

PHP Code. PHP 代码。

$output = shell_exec("python3 /var/www/python/test.py");
print_r($output);

exec('python3 --version 2>&1', $output);
var_dump($output);

Trying both shell_exe and exec尝试shell_exeexec

  1. Make sure the python file has executable permission and added to www-data group (if its ubuntu/debian systems) .确保 python 文件具有可执行权限并添加到 www-data 组(如果它的 ubuntu/debian 系统)。 sudo chmod +x test.py and sudo chgrp www-data test.py sudo chmod +x test.pysudo chgrp www-data test.py

  2. Make sure the php.ini has disabled_functions line commented or empty.确保 php.ini 的 disabled_functions 行被注释或为空。

sudo vim sudo vim /etc/php/8.0/cli/php.ini sudo vim sudo vim /etc/php/8.0/apache2/php.ini sudo vim sudo vim /etc/php/8.0/cli/php.ini sudo vim sudo vim /etc/php/8.0/apache2/php.ini

For both.对彼此而言。

I compiled a simple video to make sure others dont spend more time figuring out the problem.我编写了一个简单的视频,以确保其他人不会花费更多时间来解决问题。 https://youtu.be/t-f6b71jyoM https://youtu.be/t-f6b71jyoM

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM