Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sudo privileges within python virtualenv

Environment

  • Windows Subsystem for Linux with Serial Communication to a GPS.

  • Adafruit GPS connected to a Arduino Nano which is connected to COM10. In Windows Subsystem for Linux this is equivalent to /dev/ttyS10

  • Requirements: pyserial

I have written a simple script to read information from the GPS module:

import serial

def select_sentence():
""" This function sends serial data to the GPS module to display only GPGGA and GPRMC"""

def read_gps():
    ser = serial.Serial("/dev/ttyS10", 9600)
    while True:
         print(ser.readline().decode('utf-8'))

if __name__ == "__main__":
     select_sentence()
     read_gps()

In the virtualenv I chose Python3 and when I executed it I got Permission Error for the serial port /ttyS10 so I chose to sudo chmod 666 /dev/ttyS10 to use the script in the virtualenv.

However is there an alternative to the above mentioned chmod /dev/serial in order to avoid the PermissionErrors?

I am aware that even in the virtualenv when one uses sudo the packages installed in the virtualenv are no considered and instead sudo looks for your global pip packages.

like image 675
Shan-Desai Avatar asked May 14 '18 17:05

Shan-Desai


1 Answers

When you activate a virtualenv (by source venv/bin/activate or similar), that basically just tells your shell: "hey, when you search for a command, look in venv/bin before you look anywhere else", by updating the $PATH environment variable. That way, when you run a command like python, your shell sees and runs the python in venv/bin instead of in /usr/bin or wherever. That copy of Python is configured to look in venv/lib for packages rather than /usr/lib, so you can use the packages in your virtualenv instead of the ones installed globally.

However, when you run a program with sudo, it ignores $PATH. Why does it do that? Because in the historical days of *nix, it was common to have sudo set up so that users could execute only specific commands with it, like (say) sudo iftop1, so that anyone could check what the network was being used for, but still nobody could run sudo rm -rf /*. If sudo respected the user's $PATH, you could just copy /bin/rm to ~/bin/iftop, add ~/bin to your $PATH, then run sudo iftop – but you would actually be running rm as root!

So, sudo ignores $PATH by default. But you can still execute specific programs by giving sudo the full path to the program, so you can execute the Python in your virtualenv as root by running something like sudo ./venv/bin/python (assuming your virtualenv is called venv). That will make you root while still having access to the packages in your virtualenv, like pyserial.

1: I don't actually know of any command that would be set up like this, this is a bad example, sorry.

like image 89
ash Avatar answered Sep 28 '22 04:09

ash