I wanted to know how to run python script using php code. I have tried different options like
$output = exec("python /var/GAAutomationScript.py");
$command = escapeshellcmd('/var/GAAutomationScript.py');
$output = shell_exec($command);
But unable to run the python script. My application is in Laravel. Is it possible to run python script using Laravel scheduler jobs e.g. using artisan commands?
Some things to mention about your question :
symfony/process instead of shell_exec directly. It is already available in laravel. You can check easily if your command is successful or not and get standard output in string format etcwww-data and your python script is lets say ubuntu.nbody for example, it will then check what permissions the python script has. Are users other than ubuntu in this example are allowed to run it. symfony/process. Then run it and debug the errors. once it works then you can add that as in laravel's cron jon.See this to know mo about scheduling artisan commands.
You can also avoid creating artisan command and add shell directly, as it internally uses symfony/process. See this for that reference
You can try this for executing the Python script using Laravel's Process class (Laravel uses Process class from Symfony's Process component):
<?php
use Illuminate\Support\Facades\Process;
use Illuminate\Process\Exceptions\ProcessFailedException;
public function testPythonScript()
{
$process = new Process(['python3', '/path/to/your_script.py', 'arg1', 'arg2']);
$result = $process->run();
if (!$result->successful()) {
throw new ProcessFailedException($process);
}
$data = $result->output();
dd($data);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With