efe373
efe373

Reputation: 171

Python Multiple Simultaneous and Communicating Scripts

I have a project which will run on Raspberry Pi 4 and I have decided to use Python for scripting. I have several sensors, a camera, a screen etc.. I have written couple of scripts and I know that I can run them simultaneously by adding & at the end of the python3 <script.name> command on terminal. However, my question is this:

For example I have 2 scripts, scriptA and scriptB and both of these scripts should do something according to the other script. Let's say in scriptA I use a sensor, and when it detects something I want scriptB to do something different than usually what it does. How can I do that, how can I make these two scripts communicate in best way? I know Thumb2 assembly and interrupts, and C/C++. However, I am very new to Python. My project is not very time-critical, so I think that I do not need to use interrupts, but I do not know how to do. Thanks.

Upvotes: 0

Views: 469

Answers (1)

CobraPi
CobraPi

Reputation: 392

The better solution would be to create different classes for each process that can pass information back and fourth more efficiently, but if you are hell bent on using different scripts, you can use the os.system() call and pass in different arguments which tells the script to do something different.

For example, script_a.py calls script_b.py passing an argument to script_b.py:

script_a.py:

import os

state_change = True

if state_change:
    os.system("script_b.py 1") # you can replace 1 with any character you want
else:
    os.system("script_b.py 0")

In script_b.py, you would parse the passed in arguments and execute a corresponding action:

import sys

if sys.argv[1] == '1':
    do_something()
elif sys.argv[1] == '0':
    do_something_else()

Upvotes: 1

Related Questions