Andy Andy - 5 months ago 19
Linux Question

How to invoke sudo password request in Python

I've got a USB GPIO electronic gizmo attached to a desktop PC running Linux Mint 17 "Mate"; in this environment the gizmo appears as /dev/ttyACM0. I've written a GUI Python 2.7/Tkinter program to control the gizmo via the pySerial module. The program works when run from the console using sudo.

Being a GUI program, I want to be able to run it from the "Mate" desktop - but I can't, because being a serial device, accessing the gizmo requires root privileges obtained via sudo, wot has to be invoked at a Terminal.

# here's the offending code
import serial
numa = serial.Serial("/dev/ttyACM0", 19200, timeout=1)

How do I invoke the "Enter your password..." routine from within the Python program so a raw user doesn't have to open a Terminal to enter the password?

Thanks for any advice you can provide!


I can't answer your question, but instead I'm going to solve your problem.

When you list the device file, you'll see something like this:

$ ls -l /dev/ttyACM0
crw-rw---- 1 root dialout 188, 0 Apr  4 11:22 /dev/ttyACM0

Both the owner (root) and the owner group (dialout) have read-write-access (rw-), while everybody else isn't able to access the device (---). Therefore, instead of giving the program root access to your system, you can simply add the user(s) to the dialout group:

$ sudo usermod -aG dialout <username>

Logging out and back in will be necessary, but afterwards your script will be able to both read and write to the serial interface without the need of a root password.