I'm a newbie to Python and am trying to run a very simple Python script within Wordpress. I have followed the answers to this question but without luck.
First I created and activated a Wordpress plugin using the following php:
<?php # -*- coding: utf-8 -*-
/* Plugin Name: Python embedded */
add_shortcode( 'python', 'embed_python' );
function embed_python( $attributes )
{
$data = shortcode_atts(
[
'file' => 'firstpython.py'
],
$attributes
);
$handle = popen( __DIR__ . '/' . $data['file'], 'r' );
$read = '';
while ( ! feof( $handle ) )
{
$read .= fread( $handle, 2096 );
}
pclose( $handle );
return $read;
}
I saved the firstpython.py file in the plugin's folder which looks like this:
#!/usr/bin/python
print ("It works!")
I have verified that /usr/bin/python is the correct location through SSH.
Finally, I inserted the [python]
shortcode into a Wordpress page. But when I go to that page, there is no output at all, but no errors either.
If it makes a difference, I am using 1and1's Managed Wordpress hosting. Does anybody know where I am going wrong? I'm probably just making a rookie's mistake somewhere.
Footnote: I'm a data analyst, not a programmer, so apologies if I have misunderstood the mechanics of what I'm trying to achieve. I'm very familiar with R but installing R on a server is beyond me, hence the move to Python. I might be out of my depth here as well.
As suggested in the comments of the question you posted, depending on the machine that it is running on you might need to add #!/usr/bin/env python
at the beginning of your python script. And it seems that the first line of your script is different.