First, I have less than one year experience with Python. I normally have problems with data usage with my ISP such that I discover late that I have overused my data allocation. So, in order to evade this problem, I thought of creating a script that would run immediately I tether my phone to my PC. The script scrapes data from my ISP's website and returns my data bundle balance.
I found out that pyudev is useful in such an instance where I would like to constantly monitor my usb ports activities. Part of the script is as shown below. The problem is identify_phone
is called 3 times (from my experience) which tends to call the scraping method 3 times whereas I would like it to be called once. I tried using the global value but it does not work as expected. I have searched online but there are scarce resources on pyudev.
Any help would be appreciated (Including any revision on my code :P)
import glib
import re
import subprocess
import requests
import bs4
import datetime
import sys
from selenium import webdriver
from pyudev import Context, Monitor
def identify_phone(observer, device):
global last_updated
current_time = datetime.datetime.now()
time_diff = current_time - last_updated
if time_diff.seconds < 10:#300:
pass
else:
#print('\Checking USB ports...')
try:
tout = subprocess.check_output("lsusb | grep 1234:1234", shell=True) #check if specific usb device (phone) is connected
except subprocess.CalledProcessError:
tout = None
if tout is not None:
device_found = True
else:
device_found = False
last_updated = datetime.datetime.now()
get_network_data()# scrapes ISP website
try:
device_found = False
last_updated = datetime.datetime.now()
try:
from pyudev.glib import MonitorObserver
except ImportError:
from pyudev.glib import GUDevMonitorObserver as MonitorObserver
context = Context()
monitor = Monitor.from_netlink(context)
monitor.filter_by(subsystem='usb')
observer = MonitorObserver(monitor)
observer.connect('device-added', identify_phone)
monitor.start()
glib.MainLoop().run()
except KeyboardInterrupt:
print('\nShutdown requested.\nExiting gracefully...')
sys.exit(0)