首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过wordpress调用Python脚本?

如何通过wordpress调用Python脚本?
EN

Stack Overflow用户
提问于 2018-06-21 15:43:13
回答 3查看 1.9K关注 0票数 0

我正在为wordpress开发一个插件,用户可以上传文件并进行分析。我已经为分析准备了一个Python脚本,但是我不确定如何在PHP上运行它,同时传递参数(文件的路径)。如果有一个解决方案还能从Python脚本中读取"print“作为输出,那将是最佳的。

到目前为止,我的代码看起来像这样:

代码语言:javascript
复制
$handle = popen( __DIR__ . '/' . $data['file'], 'r' );
$read = '';

while ( ! feof( $handle ) )
{
    $read .= fread( $handle, 2096 );
}

pclose( $handle );

return $read;

但是"popen“不允许我传递参数。有关于最好的方法的线索吗?

EN

回答 3

Stack Overflow用户

发布于 2018-06-21 15:52:11

您可以使用PHP或shell_exec()函数调用Python脚本,例如,您有一个python文件hello.py,然后您可以使用以下代码调用该文件

代码语言:javascript
复制
    exec("python hello.py",$output);
    print_r($output); //display the output
票数 0
EN

Stack Overflow用户

发布于 2018-06-21 15:53:35

代码语言:javascript
复制
<?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;
}
票数 0
EN

Stack Overflow用户

发布于 2018-06-21 16:07:48

可以,你可以使用popen()函数来读写Python文件。此函数也适用于其他语言。

代码语言:javascript
复制
$handle = popen( __DIR__ . '/' . $file_name, 'r' );
$read = '';
while ( ! feof( $handle ) )
 {
   $read .= fread( $handle, 2096 );
 }
pclose( $handle );

Reference

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50963024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档