- Using Python and PHP together
- Share this:
- How to Run a Python Script from PHP
- How to Execute a Python Script in PHP
- Create a Python Script
- Create a PHP file
- Run Script
- Bonus (One More Short Demo)
- Wrap up
- PHP - How to run Python script with PHP code
- Take your skills to the next level ⚡️
- About
- Search
- Tags
- Как запустить python скрипт на php
- Читайте также
Using Python and PHP together
Today i decided to install Python in Ubuntu OS and to use PHP and Python both together. If i hadn’t installed php and wanted to have python as only localhost in my OS, so it was easy, there are plenty of examples which show how to do it(for example). But if you have already installed php and you want to have python, then let’s go on. In this sample we will need two different ports if we want to do so. And i could easily install and test it. So i am sharing how i did it:
You have installed apache2-php in your Ubuntu(or other Linux based OS) and you want to install python for having python localhost. If python has not installed in your OS, do it. Let’s open Terminal:
sudo apt-get install pythonNow you have python installed. Now we need apache mod for python. Let’s install it :
sudo apt-get install libapache2-mod-pythonThen we must make some apache operations in terminal:
cd /etc/apache2/sites-available/ sudo gedit default(default is the name of default apache conf file. )
Copy all block and paste it at the bottom. Then you will have two …. blockes. Then find in pasted block(second one) this:
Options Indexes FollowSymLinks MultiViews AllowOverride AuthConfig Order allow,deny allow from allAdd these lines to new line after “allow from all” :
AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug OnThen go to first line of pasted part and edit
Listen 81 <virtualhost:*.81>Save and close the file. Restart apache:
sudo /etc/init.d/apache2 restartIt is ready. Both PHP and Python work together in your OS. PHP has 80, Python has 81 port.
PHP – http://127.0.0.1 or http://127.0.0.1:80
You can test python with simple test file which contains these 2 strings:
def index(req): return "Python works!";In default apache virtualhost root localhost folder is /var/www. It is better to use different folders for Php and Python. For clear undersanding i am sharing my apache default conf file:
<virtualhost:*.80> ServerAdmin [email protected] DocumentRoot /home/user/public_html/ Options FollowSymLinks AllowOverride All Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 </virtualhost> Listen 81 <virtualhost:*.81> ServerAdmin [email protected] DocumentRoot /var/www/ Options FollowSymLinks AllowOverride All Options Indexes FollowSymLinks MultiViews AllowOverride AuthConfig Order allow,deny allow from all AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On # Uncomment this directive is you want to see apache2′s # default start page (in /apache2-eh) when you go to / #RedirectMatch ^/$ /apache2-eh/ ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ AllowOverride None Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch Order allow,deny Allow from all ErrorLog /var/log/apache2/error.log # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. LogLevel warn CustomLog /var/log/apache2/access.log combined Alias /doc/ "/usr/share/doc/" Options Indexes MultiViews FollowSymLinks AllowOverride None Order deny,allow Deny from all Allow from 127.0.0.0/255.0.0.0 ::1/128 </virtualhost>You can see from last sample that i use /home/user/public_html folder for PHP, and /var/www folder for Python.
That’s all. If any question, you can add it to comments.
Share this:
How to Run a Python Script from PHP
PHP (hypertext preprocessor) is a widely used free and open-source scripting language for web developers, and Python is known for its simplicity and versatility, which make it a popular choice for building complex web applications.
It would be much more convenient if we could use Python and PHP, both scripting languages, in one program.
And to run or facilitate Python scripts in PHP, we can use the “shell_exec“ function, which returns all of the output streams as a string. The shell executes it, and the result can be returned as a string.
So, let’s learn how to execute a Python script in PHP.
How to Execute a Python Script in PHP
To perform all the below steps properly, you need to install Python and a web server.
To install a web server, if you are on a Windows or Linux operating system, go for XAMPP, or else you can also manually install Apache and PHP on Linux,which is a cross-platform web server.
Create a Python Script
First, we will create a Python script file and store it in the respective directory so that it can be accessed by the PHP file when you execute the script.
For XAMPP user make sure to store file in htdocs directory of your respective web directory.
Now let’s create a short & simple program that returns “TREND OCEANS” as output.
Open a command line editor and paste the following line code where we have used the shebhang line to declare the path of the python binary file, and then we put “TREND OCEANS” under the print function to print.
#!/usr/bin/env python3 print("TREND OCEANS")
After adding the line Save and close the file with a .py extension, like here, I have saved with test.py.
Create a PHP file
To run Python Script in PHP we use two function of PHP.
escapeshellcmd() escapes all characters in a string that can trick a shell command into executing arbitrary commands.
shell_exec() that returns all of the output streams as a string.
Now we create a PHP file and save it in the same location where we have saved our python script.
Save the above script with the .php extension.
Run Script
Start your web server and visit your web server domain. In my case, I’ve demonstrated on my localhost, so I visit http://localhost with the file name sample.php on my browser.
If you perform all steps properly above output will be displayed on your browser.
Bonus (One More Short Demo)
In this method, you do not need to install a web server. You just need to have a PHP installation, and if you don’t have it, check out this guide.
Here, I do have PHP and Python installed, so let me write one more short script to print system information like hostname, platform, architecture, and date.
Open your system command line editor, paste the following lines of code, and save the file with system.py name.
#!/usr/bin/env python3 import platform from datetime import date system_hostname = platform.uname().node platform_name = platform.system() machine_arch = platform.machine() current_date = date.today() print("Hostname Info:", system_hostname) print("Platform:", platform_name) print("Machine Architecture:", machine_arch) print("Current Date:", current_date)
After that, create a new file with the name sample.php & copy and paste the following lines of script, then save the file.
Next, you have to test the functionality of the script by running the next line of commands. But before that, you need to make the script executable. Otherwise, you may get sh: 1: ./system.py: Permission denied.
To avoid this, execute the following line of code, then run the PHP file to execute the inner script.
$ chmod u+x system.py $ php system_info.php
The result of the above-mentioned procedures
Wrap up
That’s all for this guide, where I showed you how to execute or run Python scripts in PHP using the shell_exec function with two different examples.
If you have a query, feel free to ask it in the comment section.
See you in the next article…spread ☮️ and ❤️.
Innovative tech mind with 12 years of experience working as a computer programmer, web developer, and security researcher. Capable of working with a variety of technology and software solutions, and managing databases.
PHP - How to run Python script with PHP code
The shell_exec() function allows you to run a command from the shell (or terminal) and get the output as a string.
Since the function runs a command from the shell, you need to have Python installed and accessible from your computer.
PHP can’t run Python scripts directly. It just passes a command to the shell to run a Python script.
For example, suppose you have a hello.py script with the following code:
To run the script above, you need to write the following code to your PHP file:
The Python script that you want to run needs to be passed as an argument to the shell_exec() function.
The echo construct will print the output of the script execution.
If you see the shell responds with python: command not found , then that means the python program can’t be found from the shell.
You need to make sure that the python program can be found by running the which command as follows:
You may also have a Python interpreter saved as python3 , which is how Python is installed in the latest macOS version.In this case, you need to run the script using python3 in the shell_exec() function:
In a UNIX environment, you can also specify the Python interpreter in the .py file as the shebang line.
Write the interpreter you want to use for the script as follows:
With the shebang line defined, you can remove the python runner from the shell_exec() function:Now run the PHP script. You should see the same output as when you add the runner to the shell_exec() function.Sometimes you may see the shell responds with permission denied as follows:
This means that the PHP runner doesn’t have the execute permission for the Python script that you want to run.
To fix this, you need to add the execute permission to the Python script with chmod like this:
When you run the above command from the shell, the execute permission ( x ) will be added to the file.
And that’s how you can run Python script with PHP. Nice! 👍
Take your skills to the next level ⚡️
I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!
About
Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.Search
Type the keyword below and hit enter
Tags
Click to see all tutorials tagged with:
Как запустить python скрипт на php
Admin
17.09.2020
PHP, Python, WordPress
Один из способов запуска скрипта на python в PHP.
1.
В этом нам поможет команда shell_exec.ABSPATH — константа в WordPress. Если движок другой используйте $_SERVER с ‘DOCUMENT_ROOT’ или аналогичное.
$python = ABSPATH . 'wp-content/python/venv/bin/python3 ' ;
$file = ABSPATH . 'wp-content/python/script.py' ;$command = escapeshellcmd ( $python . ' ' . $file ) ;
$output = shell_exec ( $command ) ;
echo $output ;$python — это путь до интерпретатора. Тут куда вы установите, обычно он ставится на сервер в !/usr/bin/env, но можно и так.
$file — путь до файла скрипта на python
$python = ABSPATH . 'wp-content/python/venv/bin/python3 ' ;
$file = ABSPATH . 'wp-content/python/script.py' ;ob_start ( ) ; passthru ( $python . ' ' . $file . ' ' . 'аргумент' ) ; $output = ob_get_clean ( ) ;
echo $output ;На стороне python получение аргументов:
Читайте также
У сайта нет цели самоокупаться, поэтому на сайте нет рекламы. Но если вам пригодилась информация, можете лайкнуть страницу, оставить комментарий или отправить мне подарок на чашечку кофе.