How to run Python Script in Laravel?

I wanted to know how to run a python script using php code. I tried different options like

$output = exec("python /var/GAAutomationScript.py"); $command = escapeshellcmd('/var/GAAutomationScript.py'); $output = shell_exec($command); 

But failed to run python script. My application is in Laravel. Is it possible to run a python script using Laravel scheduler jobs, for example. using wizard commands?

+5
source share
2 answers

In PHP:

 <?php $command = escapeshellcmd('/usr/custom/test.py'); $output = shell_exec($command); echo $output; ?> 

In the Python file 'test.py', check this text on the first line: ( see the shebang explanation ):

 #!/usr/bin/env python 

Also, the Python file must have the correct privileges (execution for the user www-data / apache, if the PHP script is running in the browser or through curl) and / or should be "executable". Also, all commands in the .py file must have the correct privileges.

 chmod +x myscript.py 
+8
source

A few things to mention about your question:

  • I highly recommend using symfony/process instead of shell_exec directly. It is already available in Laravel. You can easily check whether your team is successful or not, and get standard output in string format, etc.
  • When you run a shell script from a web application, user rights matter. For example, the laravel web user is www-data and your python script, for example, say ubuntu.nbody , will then check what permissions the python script has. Are users other than ubuntu allowed in this example to run it?
  • Then, if you think that granting 777 permissions to the Python script will eliminate the permission problem, then this is also a risk.
  • And last but not least, create a laravel console command, add a fragment that will run the python script from symfony/process . Then run it and fix the errors. once this works, you can add this as in laravel cron jon.

See this to learn about scheduling teams of artisans.

You can also avoid creating the artisan command and add a shell directly, since it uses symfony/process internally. See this for this link.

+1
source

All Articles