Запустить скрипт python через php

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.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

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.

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?

Adamos

Зачем вообще запускать питон через пых?
Почему не настроить веб-сервер так, чтобы он обрабатывал и то, и другое, и использовать простой редирект?

ipatiev

Главная проблема музыки в России начинающих программистов в том, что они «перерывают интернет» в поисках решения своей задачи. А надо — в поисках того, как разобраться, в чем проблема.
Потому что само решение и так уже есть.

Как минимум — в начало пхп скрипта и смотреть на ошибки

ini_set('display_errors',1); error_reporting(E_ALL);

А у него скорее всего и ошибки-то нет, просто php-скрипты короткоживующими должны быть, а bot.py наоборот никогда не завершается, поэтому web-сервер тупо прибивает скрипт, и автор вопроса получает 502-й статус или что-то подобное.

ipatiev

ipatiev

Полный путь к файлу пропиши

$python = shell_exec('python PATH_TO_FILE/bot.py');
$python = shell_exec('python PATH_TO_FILE/bot.py > PATH_TO_FILE/log.txt');

Войдите, чтобы написать ответ

Почему ломается фрагмент кода?

Ошибка программы на пайтон, как исправить?

Как сохранить старое значение для input type file?

Источник

Читайте также:  font-style
Оцените статью