Call Python Functions within Wave
I have some functions built within python that I would like to use for the wave dashboard calculations. I've tried to call upon these through shell_exec within my index.blade.php file (see below) but nothing runs. I also tried auto loading the python file in the composer.json file but that didn't change anything.
Is there anyway I can call upon python files from the blade.php files?
$output = shell_exec("test.py"); echo $output;
Hi there,
There are a couple of reasons why the shell_exec
function might not be working:
- Check your
php.ini
file if you have adisable_functions
variable defined. For security reasonsshell_exec
might be in that list. If this is the case, remove theshell_exec
from the list and restart your webserver. - Make sure that the path to the
test.py
file is correct, if you just put the name of the file there, it is most likely that the file will not be in the right path.
Alternatively, I personally like the symfony/process
package to run shell commands, eg:
- Install the package:
composer require symfony/process
- Example usage:
<?php
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
$process = new Process(['python', base_path().'/path/to/script.py']);
$process->run();
// error handling
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
$output_data = $process->getOutput();
Let me know how it goes!
That worked thank you! I was able to execute my python code.
I'm now trying to figure out now how to pass variables into my python code. However, when I try to add these in it ends up not running anything. Are you familiar with how to pass variables using this?
<?php
use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;
$var = "Testing"
$process = new Process(['python', '/wamp64/www/watchdog/python/test.py', $var]);
$process->run();
// error handling
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
$output_data = $process->getOutput();
echo $output_data;
?>
Then in my test.py file I have the following:
print("Hello from python" + var)
Hey,
Happy to hear that this worked!
For the arguments, the way that you have it on the PHP side looks correct, for your Python script, I think that you need to process the arguments. You could do that using the sys
module, eg:
import sys
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
Let me know how it goes!
Thanks! I got it to work using the 'sys' module
No problem! Happy to hear that you’ve got it all working!