简体   繁体   中英

Communicating from python script to already running script

I'm having some problems with communicating between 2 Python scripts. I'm fairly new to python and raspberry pi's and i found already multiple methods which after some time to understand the method turned out to useless for me. so after some hours spend, i thought it would be better to ask more experienced people.

So i'm working on a project where i'm using a webpage to control multiple machines via a multiple Raspberry Pi. (4 per Raspberry) You can enter on the webpage the machine and how long the machine should be activated. The webpage then executes a Python Script with the machine and the time to run as arguments to the raspberry pi and activates the machine for the specified time. So far everything is working great.

I also have a small 2-line LCD screen for each Raspberry Pi. This screen should change every 10 or so seconds and show each machine on the raspberry and the time the machine is still running and then change to the next one.

So the script to show every thing on the screen is an endless loop which changes every 10 seconds but i don't know how i should properly get the new running times into a running python script.

I use the values already in the python script to activate the machines so i thought i could somehow send the informations from this script to the endless, already running LCD script.

But the most methods i found are stopping and waiting for a signal from the other script. But then it doesn't change every 10 seconds.

The only method that i know right now is to save to files and read the files in the other script xD but that isn't very elegant.

I'm thankful for every help and advise that i can get.

Kiwi

You could use a database (SQLite is a simple file-based DB system, which, at least using Perl, you can put the DB directly into memory).

Another way would be to use shared memory, whether via a module, or the file system itself.

Here's an example with one Python script writing a data structure to a JSON file to /dev/shm shared memory space, and another script reading the JSON back in as the written data structure:

Output script:

import json

file = "/dev/shm/data.json"

data = {
    "pi1_enabled": True,
    "pi1_run_mins": 30,
    "pi2_enabled": False,
    "pi2_run_mins": 30
}

with open(file, "w") as jsonfile:
    json.dump(data, jsonfile)

Input script:

import json

file = "/dev/shm/data.json"

data = json.loads(open(file).read())

print(data)

Output from input script:

{'pi1_run_mins': 30, 'pi1_enabled': True, 'pi2_enabled': False, 'pi2_run_mins': 30}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM