Php with python scripts

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.

Читайте также:  Triggerbot cs go python

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.

Run Python script from PHP result

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

Run Python script file in PHP

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.

Источник

How to Run a Python Script in PHP

PHP (which is a recursive acronym for PHP Hypertext Preprocessor) is one of the most widely used web development technologies in the world. PHP code used for developing websites and web applications can be embedded directly along with the rest of the HTML markup. This, along with a rich amount of libraries to perform system tasks, or to integrate with other application, makes PHP the go-to language for the Internet.

While there are plenty of libraries (or modules) in PHP, there can be cases when a module for a certain task is either missing or is not properly implemented; while the same module is available in Python.

Apart from this, for certain scripting tasks the user might find Python more suitable, while he finds PHP suitable for the rest of his codebase.

In this article, we will take a look at how a Python script can be run from a PHP interpreter in a Linux terminal.

Calling a Python Script in PHP

Let us consider the following PHP code (test.php).

Note: The ‘\n’ at the end of the string is a newline character, which will move the cursor to the new line for the next commands on the terminal.

Let’s now call a simple Python script ‘ test.py ’, which simply prints ‘Hello World’.

$ cat test.py print(“Hello World”) 

To call this script from PHP, use the ‘exec’ function.

We can call the script with the command line program ‘php’, which is nothing but the PHP interpreter.

$ cat test.py $ cat test.php $ php test.php

Run Python Script Using PHP

As we can see, the output of Python script test.py was displayed.

Next, let’s consider the following Python script file, ‘test2.py’, which takes one argument, a String, and prints it.

$ cat test2.py import sys print(sys.argv[1])

Now let’s call this script from PHP, passing the argument.

Execute Python Script Using PHP

As we can see, the Python Script got executed and printed the parameter value ‘Example’.

Conclusion

In this article, we saw how to call a Python script from within our PHP code. This can be used on more complex Python scripts, the output of which will be stored in the PHP variable as shown in our examples above.

This can especially be helpful when some complex Python libraries, eg. the machine learning and data science libraries, are to be used. If you have any questions or feedback, make sure you leave a comment below!

Источник

Как запустить 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 получение аргументов:

Читайте также

У сайта нет цели самоокупаться, поэтому на сайте нет рекламы. Но если вам пригодилась информация, можете лайкнуть страницу, оставить комментарий или отправить мне подарок на чашечку кофе.

Источник

Как запустить 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 получение аргументов:

Читайте также

У сайта нет цели самоокупаться, поэтому на сайте нет рекламы. Но если вам пригодилась информация, можете лайкнуть страницу, оставить комментарий или отправить мне подарок на чашечку кофе.

Источник

Оцените статью