无法从php执行python脚本

Raj*_*der 10 php python

我想从PHP文件中执行Python脚本.我能够执行简单的python脚本,如:

print("Hello World") 
Run Code Online (Sandbox Code Playgroud)

但是当我想执行以下脚本时,没有任何反应

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")
Run Code Online (Sandbox Code Playgroud)

当我从终端执行它时,同样的脚本工作正常.这是我的PHP脚本:

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

我也试过以下方法,但没有运气:

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

请帮我

hun*_*eke 4

PHP 的passthru函数没有您可能正在寻找的传递环境变量的优雅方法。如果必须使用passthru,则直接在命令中导出变量:

passthru("SOMEVAR=$yourVar PATH=$newPATH ... /path/to/executable $arg1 $arg2 ...")
Run Code Online (Sandbox Code Playgroud)

如果您倾向于shell_exec,您可能会喜欢putenv稍微干净的界面:

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

如果您愿意接受更强大(如果乏味)的方法,请考虑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 );
}
Run Code Online (Sandbox Code Playgroud)