Member-only story

How to Run a Python Script on Insertion of a USB Device

A guide to trigger a data transfer or other process when inserting a USB in Linux

Daniel Ellis Research
Better Programming
3 min readDec 2, 2020
computer with USB ports — cover image
Photo by Tobias Lystad on Unsplash.

In our latest Raspberry Pi sensor project, we wanted to have a no-network approach to getting data automatically off it. The solution for this came through the running of a Python script on insertion of an “authorised” USB storage device.

In this article, I will explain how such a feat may be achieved.

The USB Rules

The simplest part lies in providing a set of rules on what to do upon insertion. These consist of a script for when we insert a USB and one for when we remove it:

ACTION=="add", SUBSYSTEM=="usb", PROGRAM="<full_path_here>/on_usb_in.sh"
ACTION=="remove", SUBSYSTEM=="usb", PROGRAM="<full_path_here>/on_usb_out.sh"

These two lines go into the etc/udev/rules.d directory. For example:

nano /etc/udev/rules.d/custom_usb.rules

On USB Disconnect

As suggested by this post, we are able to use a LOCK file to show only when the device is plugged in and not run multiple instances of the code. This method has its drawbacks if we intend to plug multiple USBs at the same time, but this should seldom…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Daniel Ellis Research
Daniel Ellis Research

Written by Daniel Ellis Research

Research Software Engineer specialising in High-Performance Computing and Data Visualisation. — PhD in Atmospheric Chemistry and Masters in Theoretical Physics.

Responses (1)

What are your thoughts?