Link python with php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Access the power and flexibility of PHP from within Python

joshmaker/python-php

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Have you ever wished that the Python standard library had the power and flexibility of PHP? Now it is as simple as import php

Python PHP can be installed using pip

$ pip install -e git+git@github.com:joshmaker/python-php.git#egg=python-php 

To access PHP functions in Python, simply import the php module and get started.

import php php.str_replace('Python', 'PHP', 'Hello World of Python') # Output: u'Hello World of PHP'

Python PHP supports the following types: int, string, list, and dictionaries

Of course Python-PHP has unit tests! How else would we know that it is safe to use? Run tests with $ python tests.py To test with python 2.6+ and 3.3+ type $ tox

Python-PHP is compatible with all relevant Python versions: 2.6, 2.7, 3.3, 3.4 and 3.5

Is this really a good idea?

What could possibly go wrong? OK, probably a lot of things. First release on April Fools Day 2016, this project was designed as a tongue-in-cheek coding exercise intended more for mirth than productivity. Using this in production is probably a very bad idea.

About

Access the power and flexibility of PHP from within Python

Источник

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.

Читайте также:  Python change column order

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:

Источник

Какой лучший способ передачи данных между PHP и Python скриптами?

Решения, которые я пробовал, но которые мне не симпатичны:

  1. PHP скрипт отправляет данные в Python скрипт с помощью exec(«python3.7 script.py $string 2>&1», $output)$? но в этом случае Python скрипт каждый раз грузится с нуля, что очень долго. Это точно не подходит.
  2. Смог создать сервер из script.py, который ждет GET запрос на порту IP:9090 и все работает приемлемо, но мне кажется это замусоренным решением и хочется верить, что можно как-то подружить скрипты на уровне процессов linux (и это быстрее, отказоустойчивее, проще в реализации)

Простой 3 комментария

Не пробовали общаться через базу данных? То есть один записывает в БД запись, другой, делая опросы БД, дожидается появления записи, после чего считывает и удаляет запись. Обрабатывает данные и записывает их в другую таблицу. Первый всё это время делает периодические запросы к БД, и при появлении записи — считывает их и удаляет уже не нужную запись. Так как база данных постоянно пустая, то индексы в ней создавать не нужно.

Вариант два — питоновский скрипт обрастает API и ожидает запросов по API (например нестандартный порт) и сразу возвращает результат.

Дмитрий Добрышин, сокеты в разы быстрее, чем IP-порты. (но работают, разумеется, только внутри одной ОС)

syamskoy

total4c

Зёма Подушкин, если внутри одной ОС — то можно. Если по сети — тогда только TCP-сокеты.
unix — не будут работать.
Я уже писал в коментариях к вопросу, скопирую цитату:

Т.е., для межпроцессового взаимодействия между разными програмными модулями внутри одной ОС можно создать API-интерфейс на UNIX-сокетах, чтобы обеспечить максимальную скорость обмена («диалога») данными между разными процессами.
Например, при разработке микросервисов или централизованных «магистралей/шин» данных.

Решение, найденное с подсказки xmoonlight

Значит в PHP файл пихаем это:

$sock = stream_socket_client('unix:///tmp/echo.sock', $errno, $errst); fwrite($sock, $type); $response = fread($sock, 1024); fclose($sock);

А в Python файл пихаем это:

# Адрес файла, который будет мостиком для общения между PHP и Python SERVER_PATH = '/tmp/echo.sock' # Если файл уже есть, его надо удалять if os.path.exists(SERVER_PATH): os.remove(SERVER_PATH) # Создаем новый UNIX сервер server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) server_socket.bind(SERVER_PATH) server_socket.listen() while True: client, adress = server_socket.accept() message = client.recv(1024) # Печатаем входящее сообщение print('received:', message.decode("utf-8")) # Отправляем ответ client.send('This is my Response!'.encode()) client.close() server_socket.close() print('UNIX сервер закрыт!')

Источник

Connecting to MySQL with Python and PHP

The Python and PHP connection.

We all know the power of MySQL — one of the most used open source databases and a challenge to proprietary products of the genre. Python and PHP are well-known scripting languages. We combine these two powers in this article. So fasten your seatbelts, and enjoy the ride!

As you know, there are many modules and APIs in Python. For databases, there is the DB-API, the database application programming interface. To use this API with MySQL, you need to have the MySQLdb driver. It’s built into versions later than 2.3. You can also download it from its SourceForge project page and install it with the following commands:

# tar -xvf foldername.tar.gz # cd path-to-extracted-folder #python setup.py install

Note: I am using Ubuntu 10.04 32-bit on my laptop, with Python 2.7 and PHP 5.3.2. So the data provided is with respect to this configuration.

Accessing MySQL through DB-API using MySQLdb comprises the following steps:

  1. Import the MySQLdb module.
  2. Open the connection to the server.
  3. Run your queries.
  4. Close the connection.

We will undertake these steps in a script mysqlpython.py :

import MySQLdb #1 connection=MySQLdb.connect(host="servername", user="username", passwd="password", db="databasename") #2 cur=connection.cursor() #3 cur.execute("create table lfy(name varchar(40), author varchar(40))") #4 cur.execute("insert into lfy values('Foss Bytes','LFY Team')") #5 cur.execute("insert into lfy values('Connecting MySql','Ankur Aggarwal')") cur.execute("select * from lfy") #6 multiplerow=cur.fetchall() #7 print “Displaying All the Rows: “, multiplerow print multiplerow[0] cur.execute("select * from lfy") row=cur.fetchone() #8 print “Displaying the first row: “, row print "No of rows: ", cur.rowcount #9 cur.close() #10 connection.close() #11

Figure 1 below shows the output of the Python script.

Output of the Python script

A few notes with respect to the above code:

  1. We imported the MySQLdb module to use the database API.
  2. We connected to the MySQL server by calling the MySQLdb connect() function. The parameters required were the server name, MySQL username, MySQL password, and the database you want to use.
  3. To retrieve query results, we created cur , an object of the cursor() class, which will be responsible for execution and fetching.
  4. cur.execute() executes the query to create a table named lfy .
  5. We inserted values into the lfy table.
  6. We retrieved all values in the lfy table through a SELECT query.
  7. cur.fetchall() will fetch all results of the query, and return them as a nested list.
  8. cur.fetchone() will fetch one row at a time. You might wonder why we executed the SELECT query again — because fetchall() has already fetched all results of the previous query, and calling fetchone() would return None .
  9. The rowcount property tells us the number of rows returned by the query.
  10. We closed the cursor object, freeing the resources it holds.
  11. We closed the connection. Always remember to close the connections; otherwise, it may be a major security risk.

Note: Python being an interpreted language, it executes code line by line. If an error occurred on the 8th line, by then, it has executed the first seven lines, creating the table and inserting entries. The connection also remains open. Therefore, I recommend you adopt error and exception handling while using databases.

Connecting MySQL with PHP

PHP is very popular for server-side scripting, and MySQL databases are widely used for storage of the data used in dynamic pages. Connecting to MySQL from PHP is quite easy, with in-built functions; it follows the same four rules we discussed in the Python section. We will do the same basic tasks as the Python script; so before trying out the code below, drop the previous table. Here’s our PHP script, mysqlphp.php :

A detailed explanation of the above script is given below:

Output of the PHP script

  1. If the connection to MySQL fails, we use the die() function as an error-handling technique, to stop processing the page. The connection object is passed to other MySQL-related functions for use.
  2. We selected the database we want to use.
  3. We used mysql_query() to execute queries.
  4. mysql_fetch_array() will fetch the results of the query in the form of an array. We have used a while loop to display the results.
  5. To display the data, we used print_r() , which will display the whole row at one go. To access individual fields, use a string index of the field-name, like row[«name»] , etc. See the output screenshot (Figure 2) for a clearer understanding.
  6. We closed the connection to the MySQL server.

Connecting to a database is easy! So start playing with your database through scripting 🙂

Источник

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