admin管理员组

文章数量:1122846

I'm taking Harvard's CS50, I am a beginner (and enthusiast!) coder. As my final project I am making a program to keep track of when a USB device is connected to a computer, storing some values in a SQL database. Everything works fine while working in VS code and through terminal, but when I tried to implement Flask to have it renderend in a web page, problems started. Seems like Flask somehow blocks USB monitoring to start (even if it's called earlier than Flask!), I don't know why. Here's my code:

import hashlib
import pyudev
import threading

from cs50 import SQL
from datetime import datetime, timedelta
from flask import Flask, render_template

app = Flask(__name__)

db = SQL("sqlite:///lessmob.db")

def device_event_monitor(action, device):
    if device.subsystem == 'usb':
        [here my code does stuff]

def monitor_usb():
    context = pyudev.Context()
        
    monitor = pyudev.Monitor.from_netlink(context)
    monitor.filter_by('usb')  # Filtrare solo eventi di dispositivi USB

    monitor.enable_receiving()

    print("Waiting for USB devices...")

    observer = pyudev.MonitorObserver(monitor, device_event_monitor)
    observer.start()

    try:
        while True:
            pass
    except KeyboardInterrupt:
        print("\nMonitoraggio terminato.")

@app.route("/")
def index():
    return render_template("index.html")

if __name__ == "__main__":
    usb_thread = threading.Thread(target=monitor_usb)
    usb_thread.start()

    app.run(debug=True)

When I type flask run, I DOES NOT see in terminal the message "Waiting for USB devices...", but Flask starts without any problems. Why?? Thanks in advice for help and many greetings from Italy!

I tried running my code in several environment (Windows, Linux, codespace), nothing changed.

本文标签: pythonProblem with pyudev USB monitoring in FlaskStack Overflow