skip to Main Content

I am working on a song playing project and got stuck. Is there a way of passing a variable from php to python. I am working on a wordpress website and in some parts I used Python code and used php plugin to get the code working on that website. But here is the thing because I constantly need to copy the script and make new versions of it because I have to specify the path to the song and then insert the plugin into the website. So I was wondering if there is a way in which I could add this path to the python script trough php (meaning that I vould insert the path in php code instead of python)?

This is my plugin:

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

Is this even possible? Any ideas?

2

Answers


  1. In my understanding after you have installed the WP plugin then you can execute the python code in your WP by the following shortcode:

    [python file="hello.py"]
    
    

    Please either (1) save the variable to a TXT file by PHP and then in your hello.py read the TXT file to get the data value ;

    or (2) save the variable to Mysql database table by PHP and then in your hello.py read the Mysql database table. reference link

    Login or Signup to reply.
  2. You shouldn’t be actually using python code inside php scripts since it can really mess up with your compiler.
    You should CALL THE EXECUTION of the script by using this

    Then you could provide arguments to execute python scripts :

    python3 hello.py arg1 arg2
    

    And then from python script you would get arguments like this:

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

    Edit : its a follow up from Ken Lee’s comment

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search