Skip to content

Instantly share code, notes, and snippets.

@djhunter67
Created October 12, 2022 12:26
Show Gist options
  • Save djhunter67/b9d78c393918055a4db4d2ae9d9e0b7b to your computer and use it in GitHub Desktop.
Save djhunter67/b9d78c393918055a4db4d2ae9d9e0b7b to your computer and use it in GitHub Desktop.
Find USB devices such as micro-controllers when plugged into the Linux system. Allows user to choose a device. Test on Arch Linux.
import subprocess
DEVICE_PORT = 0
def find_device(DEVICE_NUMBER: int = DEVICE_PORT) -> tuple[str, list[str]]:
"""Find the Megatron device plugged into the Linux computer"""
# Search Linux filesystem for device
find_acm = ["find /dev -name 'ttyACM*'"]
find_usb = ["find /dev -name 'ttyUSB*'"]
results_acm = subprocess.run(
args=find_acm,
shell=True,
stdout=subprocess.PIPE,
universal_newlines=True,
encoding="utf-8",
capture_output=False,
)
results_usb = subprocess.run(
args=find_usb,
shell=True,
stdout=subprocess.PIPE,
universal_newlines=True,
encoding="utf-8",
capture_output=False,
)
# Split the results into a list
results_acm = results_acm.stdout.split("\n")
results_usb = results_usb.stdout.split("\n")
# Remove empty strings
results_acm = [x for x in results_acm if x]
results_usb = [x for x in results_usb if x]
# Check if the device is in the list
if DEVICE_NUMBER < len(results_acm):
device = results_acm[DEVICE_NUMBER]
elif DEVICE_NUMBER < len(results_usb):
device = results_usb[DEVICE_NUMBER]
else:
raise IndexError("Device not found")
# Return the device and the list of devices
return device, results_acm + results_usb
def main():
"""Main function"""
device, devices = find_device()
print(f"Device: {device}")
print(f"Devices: {devices}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment