Share variables between python & php

1.1k views Asked by At

I have a script in python receiving continuously data from sensors.

I need to publish the last data at request on a webpage using php.

Apache, php and python are all on the same linux install (actually on an raspberry).

I'm not interested in storing previous data and I'm a bit concerned about data corruption on writing on SD. I would prefer to reduce complexity and increase speed refresh (avoid sql).

Could a text file written in ramfs / tmpfs solve the problem? or there is a method to share memory like memcache to share also global variables?

enter image description here

Any practical example or howto will be really well-accepted.

4

There are 4 answers

0
arunk2 On

Clearly memcache as a means to share data different application will work. You will not have any corrupted data for sure as all the memcache operation are atomic. memcache atomic discussion could be useful.

On memcached's FAQ:

Is memcached atomic? Aside from any bugs you may come across, yes all commands are internally atomic. Issuing multiple sets at the same time has no ill effect, aside from the last one in being the one that sticks.

Note: Running memcache service might consume considerable amount of memory.

Hope it helps!

0
DhruvPathak On

You can use any interoperable format like json or msgpack. Whenever you generate data in python, add it to a caching layer like memcache/redis using json format ( and preferably a gzip compressed version), then your PHP script can unserialize the json data and display it in the app.

0
super_ylam On

I think you may try System V shared memory.

As example:

In Python side: python -m pip install sysv_ipc

then somewhere in the python script:

import sysv_ipc
...
KEY=20171220
sysv_memory=sysv_ipc.SharedMemory(KEY, sysv_ipc.IPC_CREAT, 0666, 256)
...
sysv_memory.write('1234'+'\0')

Then in the PHP side:

$SHARED_MEMORY_KEY = 20171220;
...
$shmId = shmop_open($SHARED_MEMORY_KEY, 'a', 0666, 256);
...
$test_string = shmop_read($shmId, 0, 0);

I can get the $test_string as '1234' successfully in PHP.

0
Mike On

Here is a solution using memcached that works on Raspbian 10 (buster), PHP 7.3.19, and Python 3.7.3:

1. Install memcached

apt-get install memcached php-memcached
pip install pymemcache

These commands install memchached server and client modules for PHP and Python.

2. PHP code

$m = new Memcached();

// connect
$m->addServer('127.0.0.1', 11211);

// get a value
$value = $m->get('key');

// set a value
$m->set('key', 'value');

// clean up
$m->quit();

3. Python code

from pymemcache.client import base

# connect
m = base.Client(('127.0.0.1', 11211))

# get a value
value = m.get('key')

# set a value
m.set('key', 'value')

# clean up
m.close()

Note:

I used default memcached settings here. If you need to change them edit sudo nano /etc/memcached.conf and restart the daemon: sudo /etc/init.d/memcached restart.