php - 无法从php执行python脚本

标签 php python

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

print("Hello World") 

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

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")

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

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

我也尝试过以下方法,但没有成功:

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

请帮帮我

最佳答案

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

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

如果您倾向于使用 shell_exec,您可能会喜欢 putenv 稍微更简洁的界面:

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

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

关于php - 无法从php执行python脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49032661/

相关文章:

python - Django休息框架: ModelSerializer as field in a ModelSerializer doesn't show choices

python - 匹配 SINXX11-111111 的正则表达式

php - 使用 Eloquent 保护数据透视表免受质量分配

php - 在 Propel 中使用 GROUP_CONCAT (MySQl) 和 WM_CONCAT (Oracle)

php - jQuery 中的 JavaScript 函数参数

javascript - file_put_contents 与 jquery 重新加载?

php - 在 PHP 中我该如何写 : IS NOT SMALLER THAN

python - 如何有效计算大型点云中 3D 法线的方向

python - 如何在 Pyglet 中加载同一系列的字体变体?

python - 如何更新 csv 值,因为它们的行号和列号是 python 已知的