我正在为wordpress开发一个插件,用户可以上传文件并进行分析。我已经为分析准备了一个Python脚本,但是我不确定如何在PHP上运行它,同时传递参数(文件的路径)。如果有一个解决方案还能从Python脚本中读取"print“作为输出,那将是最佳的。
到目前为止,我的代码看起来像这样:
$handle = popen( __DIR__ . '/' . $data['file'], 'r' );
$read = '';
while ( ! feof( $handle ) )
{
$read .= fread( $handle, 2096 );
}
pclose( $handle );
return $read;但是"popen“不允许我传递参数。有关于最好的方法的线索吗?
发布于 2018-06-21 15:52:11
您可以使用PHP或shell_exec()函数调用Python脚本,例如,您有一个python文件hello.py,然后您可以使用以下代码调用该文件
exec("python hello.py",$output);
print_r($output); //display the output发布于 2018-06-21 15:53:35
<?php # -*- coding: utf-8 -*-
/* Plugin Name: Python embedded */
add_shortcode( 'python', 'embed_python' );
function embed_python( $attributes )
{
$data = shortcode_atts(
[
'file' => 'hello.py'
],
$attributes
);
$handle = popen( __DIR__ . '/' . $data['file'], 'r' );
$read = '';
while ( ! feof( $handle ) )
{
$read .= fread( $handle, 2096 );
}
pclose( $handle );
return $read;
}发布于 2018-06-21 16:07:48
可以,你可以使用popen()函数来读写Python文件。此函数也适用于其他语言。
$handle = popen( __DIR__ . '/' . $file_name, 'r' );
$read = '';
while ( ! feof( $handle ) )
{
$read .= fread( $handle, 2096 );
}
pclose( $handle );https://stackoverflow.com/questions/50963024
复制相似问题