Reputation:
I'm currently working on a project that involves an Up-board running ubilinux connected to three usb devices. We have witnessed issues where the board sees the usb device disconnect. When the usb device reconnects, it loads the USBSerial and FTDI_sio module, which is an issue. Before the program can check for the presence of the connected devices I need to run
sudo /sbin/rmmod usbserial
sudo /sbin/rmmod ftdi_sio
I don't want the program to constantly perform those operations, so what I've done is created a thread that looks for a usb device being plugged in. I'm using pyudev to accomplish this.
My issue is that I don't always have to perform the rmmod for usbserial and ftdi_sio, as they don't always load when the usb device is attached. Is there some way to run a check, written in python, to determine if ftdi_sio and usbserial have loaded?
I've done a number of searches and I find a number of links that show how to do it as a bash script, but I'm trying to find out if I can do it in python. I also seem to get a large number of search results for loading python modules, which isn't very helpful.
Upvotes: 4
Views: 3629
Reputation: 3828
Here's some Popen
code to check if it's loaded using lsmod
:
import subprocess
def module_loaded(module_name):
"""Checks if module is loaded"""
lsmod_proc = subprocess.Popen(['lsmod'], stdout=subprocess.PIPE)
grep_proc = subprocess.Popen(['grep', module_name], stdin=lsmod_proc.stdout)
grep_proc.communicate() # Block until finished
return grep_proc.returncode == 0
for module_name in ['usbserial', 'ftdi_sio']:
loaded = module_loaded(module_name)
print('Module {} {} loaded'.format(module_name, "is" if loaded else "isn't"))
The print is there just to prove it works; you can replace that with your rmmod
code. Output:
Module usbserial isn't loaded
ftdi_sio 52791 0
Module ftdi_sio is loaded
I went with modinfo
to begin with btw, but that didn't work as intended. modinfo
would show the module info regardless of whether or not it was loaded. The lsmod
approach appears to work well though.
Upvotes: 3