Quiero ejecutar el script de Python desde un archivo PHP. Puedo ejecutar un script de python simple como:
print("Hello World")pero cuando quiero ejecutar el siguiente script, no pasa nada
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")y el mismo script funciona bien cuando lo ejecuto desde la terminal. aquí está mi script php:
$output = shell_exec("/usr/bin/python /var/www/dev.com/public_html/index.py"); echo $output;También probé el siguiente método pero no tuve suerte:
$output = array(); $output = passthru("/usr/bin/python /var/www/dev.com/public_html/index.py"); print_r($output);por favor, ayúdame
La función passthru de PHP no tiene el método elegante para el que puede estar buscando pasar variables de entorno. Si debe usar passthru , exporte sus variables directamente en el comando:
passthru("SOMEVAR=$yourVar PATH=$newPATH ... /path/to/executable $arg1 $arg2 ...") Si se inclina por shell_exec , puede apreciar putenv por la interfaz un poco más limpia:
putenv("SOMEVAR=$yourVar"); putenv("PATH=$newPATH"); echo shell_exec("/path/to/executable $arg1 $arg2 ..."); Si está abierto a un enfoque más robusto (aunque tedioso), considere 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 ); }Acceda a su respuesta, ya que desea ejecutar el script de python desde PHP
Pude ejecutarlo usando el siguiente código.
$command = escapeshellcmd('/var/www/yourscript.py'); $output = shell_exec($command); echo $output;Utilice el código PHP anterior con el mismo script de Python. Primero intente ejecutar el script de python como un script de GCI para asegurarse de que funciona y configure los permisos para el directorio público y el script como mencioné antes.
=====================================================
Por lo que preguntó, supongo que esto es lo que está tratando de hacer: está tratando de ejecutarlo como un script CGI como http://localhost/yourscript.py
¿Y por qué está utilizando PHP para ejecutar secuencias de comandos de Python cuando puede ejecutarlo directamente como una secuencia de comandos CGI?
Esto es lo que debe hacer para que funcione como una página web:
#!/usr/local/bin/python
desde pydub importar AudioSegment
AudioSegment.converter = "/usr/local/bin/ffmpeg"
sonido = AudioSegment.from_file("/var/www/dev.com/public_html/track.mp3")
sonido.export("/var/www/dev.com/public_html/test.mp3", format="mp3", bitrate="96k")
imprimir "Tipo de contenido: texto/html"
imprimir
imprimir ""
imprimir ""
imprimir ""
imprimir "Listo/puede realizar algunas condiciones e imprimir información útil aquí"
imprimir ""
Pude ejecutar esto correctamente. avisame si no es tu caso si quieres otra cosa
En mi caso, hice este código.
<?php chdir('/home/pythontest') ; // python code dir $commandline="/usr/bin/python3 test.py parameter" ; exec($commandline, $output, $error) ; echo $output ; ?>Si necesita configurar algunos entornos para python, agregue vars de entorno como este.
$commmandline="LANG=en_US.utf8 LC_ALL=en_US.utf8 /usr/bin/python3 ..." ;y verifique el registro de httpd.