gpt4 book ai didi

php - 无法从php执行python脚本

转载 作者:太空狗 更新时间:2023-10-29 20:23:36 24 4
gpt4 key购买 nike

我想从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com