无法从php执行python脚本

时间:2021-08-09 04:39:53

I want to execute Python script from PHP file. I am able to execute simple python script like:

我想从PHP文件中执行Python脚本。我能够执行简单的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

请帮我

5 个解决方案

#1


4  

PHP's passthru function does not have the elegant method for which you may be searching of passing environment variables. If you must use passthru, then export your variables directly in the command:

PHP的passthru函数没有您可能正在搜索传递环境变量的优雅方法。如果必须使用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 );
}

#2


1  

Acc to your reply, as you want to execute the python script from PHP

当您希望从PHP执行python脚本时,请将Acc发送给您的回复

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. 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

请使用上面的PHP代码和相同的python脚本。首先尝试将python脚本作为GCI脚本运行,以确保它正常工作,并将权限设置为公共目录和脚本,如我前面提到的那样

===================old ans============================

= = = = = = = = = = = = = = = = = = =老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 ).
  2. 在apache(或正在使用的web服务器)中启用python CGI。
  3. put the script in CGI configured directory
  4. 将脚本放入CGI配置的目录中。
  5. add proper code to your script to make it work as a CGI script
  6. 将适当的代码添加到脚本中,使其作为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. 赋予脚本权限并使公共目录可写
  3. Access the script http://localhost/your-path-to-script.py
  4. 访问脚本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

我能正常运行这个。如果你想要别的东西,请告诉我。

#3


1  

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设置一些环境,那么添加这样的环境vars。

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

and check the httpd log.

并检查httpd日志。

#4


1  

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文件中,最好不要给apache提供sudo,而是给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:

让它executabe:

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

then try it:

然后试一试:

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

I hope this will work! :)

我希望这行得通!:)

#5


0  

You can also exec ffmpeg directly without python:

您也可以直接执行ffmpeg,没有python:

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

ffmpeg docs

ffmpeg文档

#1


4  

PHP's passthru function does not have the elegant method for which you may be searching of passing environment variables. If you must use passthru, then export your variables directly in the command:

PHP的passthru函数没有您可能正在搜索传递环境变量的优雅方法。如果必须使用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 );
}

#2


1  

Acc to your reply, as you want to execute the python script from PHP

当您希望从PHP执行python脚本时,请将Acc发送给您的回复

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. 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

请使用上面的PHP代码和相同的python脚本。首先尝试将python脚本作为GCI脚本运行,以确保它正常工作,并将权限设置为公共目录和脚本,如我前面提到的那样

===================old ans============================

= = = = = = = = = = = = = = = = = = =老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 ).
  2. 在apache(或正在使用的web服务器)中启用python CGI。
  3. put the script in CGI configured directory
  4. 将脚本放入CGI配置的目录中。
  5. add proper code to your script to make it work as a CGI script
  6. 将适当的代码添加到脚本中,使其作为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. 赋予脚本权限并使公共目录可写
  3. Access the script http://localhost/your-path-to-script.py
  4. 访问脚本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

我能正常运行这个。如果你想要别的东西,请告诉我。

#3


1  

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设置一些环境,那么添加这样的环境vars。

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

and check the httpd log.

并检查httpd日志。

#4


1  

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文件中,最好不要给apache提供sudo,而是给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:

让它executabe:

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

then try it:

然后试一试:

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

I hope this will work! :)

我希望这行得通!:)

#5


0  

You can also exec ffmpeg directly without python:

您也可以直接执行ffmpeg,没有python:

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

ffmpeg docs

ffmpeg文档