Python and PHP are both popular programming languages. While PHP is useful for building websites, python is great at performing heavy duty tasks in background. Sometimes you may need to run python script from PHP. In this article, we will learn how to do this. There are a couple of simple ways to run python code from PHP. We will look at each of them one by one.
How to Run Python Script from PHP
Let us say you have the following Python script.
$ vi /home/ubuntu/test.py
Add the following line to it followed by your required python code.
Save and close the file. Modify its permissions to make it executable.
$ chmod +x /home/ubuntu/test.py
In the PHP file where you want to run the above python code, add the following PHP code.
<?php $command = escapeshellcmd('/home/ubuntu/test.py'); $output = shell_exec($command); echo $output; ?>
In the above code, we first define a command to run python script using escapeshellcmd() function. Then we call shell_exec() function to run the command. You can use this approach for not just python scripts but also other scripting languages such as perl, ruby and also shell scripts. You can also use this to run shell commands with or without arguments and options.
In this article, we have learnt how to run python script from PHP. It is useful if you want to run any python code, and also other shell commands from PHP.
How to Convert All Strings in List to Integer in Python
How to Uninstall Python 2.7 on Mac OS
How to Parse URL into Hostname & Pathname
How to Remove Element By ID in JS
How to Write to File in NodeJS