1

I have 2 tasks that are executed separately and each has its own python file.

One task is to monitor the gpio. What it does is count how many times a button is pressed. I have to run this forever and used linux command nohup to run this in background.

I have another python file that simply displays a menu. Like below.

Please choose:
1. Display button press count.
2. Reset button press counter.
3. Quit.

I'm just starting to learn python. So my question now is how can I make this into one file or 1 single task if possible. Simply put, how can I display the menu and do the monitoring at the same time.

Pardon me if this is terribly the wrong way of doing things. I'm open to any suggestions.

  • I think you need to include your existing Python programmes before you can hope to gain any constructive advice... – SlySven Dec 17 '17 at 1:16
  • @SlySven, no, I just need the idea... Already got it. – Reigel Dec 17 '17 at 7:41
3

You can use Thread. Here is an exemple:

from threading import Thread
import time

class Thread1(Thread):
    def __init__(self, ):
        Thread.__init__(self)

def run(self):
    #Do stuff


class Thread2(Thread):
    def __init__(self):
        Thread.__init__(self)

def run(self):
    #Do other stuff


thread_1 = Thread1()  # initialise
thread_2 = Thread2()  # initialise
thread_1.start()
time.sleep(1)
thread_2.start()

The only problem I have when I use thread is to kill the program. I found a solution (not the best), the solution is to kill the thread with: pkill -f -9 programName.py

  • Thanks! Can threading share variables or should I use something like database? I need the counter to be visible in both tasks... one to update and the other to read from it. – Reigel Dec 13 '17 at 8:39
  • Yes, You can use a global variable in other functions by declaring it as global in each function that assigns to it. check this link for exemple – Kreumz Dec 13 '17 at 8:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.