How to use python subprocess.check_output with root / sudo privileges

I am writing a Python script that will run on Raspberry, which will read the temperature from the sensor and write to Thingspeak. I am working with a bash script, but I will not do it with Python, as it will be easier to manipulate and check read values. The sensor is read using a library called loldht. I tried to do it like this:

from subprocess import STDOUT, check_output
output = check_output("/home/pi/bin/lol_dht22/loldht", timeout=10)

The problem is that I need to run the library using sudo in order to be able to access contacts. I ran the script as cron. Is it possible to run this with sudo?

Or could I create a bash script that runs 'sudo loldht' and then run the bash script from python?

+4
source share
3 answers

I ran the script as cron. Is it possible to run this with sudo?

You can put python script.pyin a cron a user with sufficient rights (for example, root or a user with permissions on files and devices)

I don’t know which OS you are using, but if Raspbian is close to Debian, there is no need for sudo or root, just use a user with sufficient permissions.

I think I can do it too check_output check_output(["sudo", "/home/pi/bin/lol_dht22/loldht", "7"], timeout=10)

Of course, but the unix user that will reference this Python script will need the sudo privilege (otherwise it cannot call sudofrom subprocess). In this case, you can also do as described above, run cron from the user with the necessary permissions.

+4
source

sudo cron. sudo crontab -e, cron, .

+2

root. root , .

- .

, WiringPi. , /dev/gpiomem ( /dev/mem).

raspbian udev. . , .

You can give each user access to /dev/gpiomemother gpio devices by creating a file, for example. /etc/udev/rules.d/local.rulesand putting the following text in it:

ACTION=="add", KERNEL=="gpio*", MODE="0666"
ACTION=="add", KERNEL=="i2c-[0-9]*", MODE="0666"

The first line makes gpio devices available as well as the second I2C device.

+1
source

Source: https://habr.com/ru/post/1622464/


All Articles