【问题标题】:PHP - Is it possible to pass a variable from php to Python?PHP - 是否可以将变量从 php 传递到 Python?
【发布时间】:2021-07-31 13:06:30
【问题描述】:

我正在做一个歌曲播放项目并且卡住了。有没有办法将变量从 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;
}

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

【问题讨论】:

  • 如何运行 Python 脚本?
  • 刚刚添加了插件脚本

标签: python php wordpress plugins


【解决方案1】:

您实际上不应该在 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 评论的跟进

【讨论】:

  • 谢谢,这很有帮助,但我不明白这些论点是如何工作的。有没有关于它的视频
  • 所有东西都有一个 youtube 视频 :) youtube.com/watch?v=G10Q8vKvQyc
【解决方案2】:

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

[python file="hello.py"]

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

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

【讨论】:

  • 感谢您的信息,但是否可以只在 php 中插入 python 代码?
  • 为了直接执行 python thru php,你可以使用 shell exec reference。 Python 能够将参数作为参数读取reference
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 2018-10-22
  • 2012-10-07
相关资源
最近更新 更多