PHP - 是否可以将变量从 php 传递到 Python?

PHP - Is it possible to pass a variable from php to Python?

我正在做一个歌曲播放项目,但卡住了。有没有办法将变量从 php 传递到 python。我在一个 wordpress 网站上工作,在某些部分我使用 Python 代码并使用 php 插件让代码在该网站上运行。但事情是这样的,因为我经常需要复制脚本并制作它的新版本,因为我必须指定歌曲的路径,然后将插件插入网站。所以我想知道是否有一种方法可以通过 php 将此路径添加到 python 脚本中(这意味着我将在 php 代码中插入路径而不是 python)?

这是我的插件:

<?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;
}

这可能吗?有什么想法吗?

据我了解,在安装 WP 插件后,您可以通过以下短代码在 WP 中执行 python 代码:

[python file="hello.py"]

请 (1) 通过 PHP 将变量保存到 TXT 文件,然后在您的 hello.py 中读取 TXT 文件以获取数据值;

或 (2) 通过 PHP 将变量保存到 Mysql 数据库 table 然后在你的 hello.py 中读取 Mysql 数据库 table. reference link

您实际上不应该在 php 脚本中使用 python 代码,因为它确实会扰乱您的编译器。 您应该使用 this

调用脚本的执行

然后你可以提供参数来执行 python 脚本 :

python3 hello.py arg1 arg2

然后从 python 脚本你会得到这样的参数:

import sys
#sys.argv[0] is the name of the file ( hello.py )
arg1 = sys.argv[1]
arg2 = sys.argv[2]
...

编辑:这是 Ken Lee 评论的跟进