Running Python using sudo fails to play sound file - python

I'm using a Raspberry Pi to run a python script that both plays a sound (using pygame) and uses the onboard GPIO. I know to access the GPIO the script must be ran using sudo, but I've noticed that using sudo python myscript.py the code executes, but does not play the sound. Using python myscript.py the sound plays, but obviously the not GPIO. I've tried changing where I am referencing the audio file to an absolute path to no avail, I'm not overly familiar with inner workings of sudo, can anyone shed some light on this problem?
import pygame
pygame.init()
pygame.mixer.music.load("alert.wav")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
GPIO.output(16,True)
GPIO.output(18,True)
Output of printenv
LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:
SSH_CONNECTION=192.168.0.114 64152 192.168.0.196 22
LANG=en_US.UTF-8
INFINALITY_FT_CHROMEOS_STYLE_SHARPENING_STRENGTH=0
INFINALITY_FT_AUTOHINT_INCREASE_GLYPH_HEIGHTS=true
INFINALITY_FT_CONTRAST=0
INFINALITY_FT_STEM_FITTING_STRENGTH=25
INFINALITY_FT_GLOBAL_EMBOLDEN_X_VALUE=0
XDG_SESSION_ID=c5
USER=pi
INFINALITY_FT_AUTOHINT_SNAP_STEM_HEIGHT=100
INFINALITY_FT_GRAYSCALE_FILTER_STRENGTH=0
INFINALITY_FT_GAMMA_CORRECTION=0 100
PWD=/home/pi
HOME=/home/pi
TEXTDOMAIN=Linux-PAM
SSH_CLIENT=192.168.0.114 64152 22
INFINALITY_FT_WINDOWS_STYLE_SHARPENING_STRENGTH=10
SSH_TTY=/dev/pts/1
INFINALITY_FT_BRIGHTNESS=0
MAIL=/var/mail/pi
TERM=xterm
SHELL=/bin/bash
INFINALITY_FT_USE_VARIOUS_TWEAKS=true
SHLVL=1
INFINALITY_FT_BOLD_EMBOLDEN_Y_VALUE=0
INFINALITY_FT_GLOBAL_EMBOLDEN_Y_VALUE=0
INFINALITY_FT_AUTOHINT_HORIZONTAL_STEM_DARKEN_STRENGTH=10
LOGNAME=pi
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
XDG_RUNTIME_DIR=/run/user/1000
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games
INFINALITY_FT_FILTER_PARAMS=11 22 38 22 11
INFINALITY_FT_USE_KNOWN_SETTINGS_ON_SELECTED_FONTS=true
INFINALITY_FT_STEM_SNAPPING_SLIDING_SCALE=40
INFINALITY_FT_STEM_ALIGNMENT_STRENGTH=25
INFINALITY_FT_BOLD_EMBOLDEN_X_VALUE=0
INFINALITY_FT_AUTOHINT_VERTICAL_STEM_DARKEN_STRENGTH=25
INFINALITY_FT_FRINGE_FILTER_STRENGTH=0
_=/usr/bin/printenv
Output of sudo printenv
LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:
LANG=en_US.UTF-8
TERM=xterm
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
MAIL=/var/mail/root
LOGNAME=root
USER=root
USERNAME=root
HOME=/root
SHELL=/bin/bash
SUDO_COMMAND=/usr/bin/printenv
SUDO_USER=pi
SUDO_UID=1000
SUDO_GID=1000

Another solution that doesn't require sudo, would be to create and use a gpio group. On raspbian, you can create a new group with groupadd.
Assign that group to the gpio devices with group read/write access for that group. You can do that with chown, but that won't last after a reboot.
On raspbian this is done with permanently a udev rule. See e.g. this example.
Then add the user-id that runs the Python programs to that group. On Raspbian this is done with adduser.
Note that if you're not running the raspbian distribution, the names of the relevant commands might be different.
With this set-up every user that is part of the gpio group can access the GPIO devices.

Related

Denied persmission to .py file on ev3dev, PuTTY

I have EV3 Lego Mindstorms and I instaled on it ev3dev operating system. I set the connection with the PC via SSH and using PuTTY I started to "programming". I used the cat > test2.py and wrote this code:
#!/usr/bin/env python3
import ev3dev.ev3 as ev3
motor = ev3.LargeMotor('outA')
motor.run_timed(time_sp = 1000, speed_sp = 500)
I saved the file and initialized it using ./test2.py. I got this output:
-bash: ./test2.py: Persmission denied
What caused it and what should I change?
try this:
sudo python3 test2.py
that will allows you to open almost anything in linux
Use ls -la ./test2.py in order to see the file permissions.
Look at the beginning of the output, you'll see something like this:
-rw-rw-r--
The first - means if is a directory or a file. In this case means that is a file.
Now If you observe the remaining chars there are 3 sets of 3 chars with means the permissions for the owner of the file, the owner group and the last set is for the rest of the users.
We have permissions to read, write and execute and in the example I showed there are read and write permissions for the owner user and the owner group but non permissions for the other users.
As Is said above you can just use sudo every time you execute the script but to run it with root privileges. However I would recommend you change your file permissions and using chmod
sudo chmod +x ./test2.py
This will let you execute the script. Take a look at chmod documentation to learn more: https://help.ubuntu.com/community/FilePermissions

How can I put my python code in startup in raspberry pi

I wanted to put my python code in boot in raspberry pi.
I tried rc.local, ./bashrc but while booting program is working & I am using opencv + camera +voice command. That's not working in boot.
Please give me a way to run voice + camera + opencv + python code in boot.
I would suggest to make it run as a service as mentioned in method 4 of following article:
https://www.dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startup/
Step 1– Create A Unit File
Open a sample unit file using the command as shown below:
sudo nano /lib/systemd/system/sample.service
Add in the following text :
[Unit]
Description=My Sample Service
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/python /home/pi/sample.py
[Install]
WantedBy=multi-user.target
You should save and exit the nano editor.
This defines a new service called “Sample Service” and we are requesting that it is launched once the multi-user environment is available. The “ExecStart” parameter is used to specify the command we want to run. The “Type” is set to “idle” to ensure that the ExecStart command is run only when everything else has loaded. Note that the paths are absolute and define the complete location of Python as well as the location of our Python script.
In order to store the script’s text output in a log file you can change the ExecStart line to:
ExecStart=/usr/bin/python /home/pi/sample.py > /home/pi/sample.log 2>&1
The permission on the unit file needs to be set to 644 :
sudo chmod 644 /lib/systemd/system/sample.service
Step 2 – Configure systemd
Now the unit file has been defined we can tell systemd to start it during the boot sequence :
sudo systemctl daemon-reload
sudo systemctl enable sample.service
Reboot the Pi and your custom service should run:
sudo reboot

How to run Kivy app using sudo?

I am writing an app in Kivy and a part of the app is to turn off the rpi display's back-light after a certain amount of time and to turn the back-light back on when pressing an invisible button. I need to use sudo python when launching the app in order to open the file:
/sys/class/backlight/rpi-backlight/bl_power
The problem is that by default, I get an error saying "no module named kivy.app" when using 'sudo python'. If I add the line:
Defaults env_keep += "PYTHONPATH"
to the /etc/sudoers file it allows me to run the app with 'sudo python', but then none of the buttons on the app function. The app runs, but touch functionality is lost. Is there a way to make this work?
I'd suggest a different approach: make /sys/class/backlight/rpi-backlight/bl_power writable to the user running the Python script (most likely pi). Temporarily, this can be done with
sudo chmod a+w /sys/class/backlight/rpi_backlight/bl_power
(this grants write rights to all users). But this will also be reset at the next restart. The solution for that is to write a udev rule. They live in /etc/udev/rules.d and on my system, 99-com.rules was a good starting point. Here is what I have in a file called 98-backlight.rules:
SUBSYSTEM=="backlight", PROGRAM="/bin/sh -c 'chown -R root:video /sys/class/backlight && chmod -R 770 /sys/class/backlight; chown -R root:video /sys/devices/platform/rpi_backlight && chmod -R 770 /sys/devices/platform/rpi_backlight'"
This changes the owner group to video and grants group write rights. User pi is by default member of video. Then all you need is a restart (or sudo udevadm control --reload-rules followed by sudo udevadm trigger) to activate the new rule.

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.
Use gksudo rather than sudo
from subprocess import call
call('gksudo -D "Program requires root priveledge \nSudo "your command here",shell=True)
for example:
call('gksudo -D "Override Sudo message " cp /etc/hosts /home/new.hosts',shell=True)

Run Python script at startup in Ubuntu

I have a short Python script that needs to run at startup - Ubuntu 13.10. I have tried everything I can think of but can't get it to run. The script:
#!/usr/bin/python
import time
with open("/home/username/Desktop/startup.txt", 'a') as f:
f.write(str(time.time()) + " It worked!")
(The actual script is a bit different, as I'm just using this for testing purposes, but you get the idea.)
I've tried all of the following, with no luck:
Put the command python startuptest.py in crontab, as #reboot
python /home/username/Documents/startuptest.py, both as the regular user and as sudo
Put the command python /home/username/Documents/startuptest.py in /etc/rc.local
Opened Ubuntu's Startup Applications and put the command there
Done all of the preceding, putting the command into a shell script
and calling that shell script instead
Nothing works. I get the feeling I'm missing something simple. Any ideas? (The script runs fine if I just run the command from a terminal.)
Instructions
Copy the python file to /bin:
sudo cp -i /path/to/your_script.py /bin
Add A New Cron Job:
sudo crontab -e
Scroll to the bottom and add the following line (after all the #'s):
#reboot python /bin/your_script.py &
The “&” at the end of the line means the command is run in the background and it won’t stop the system booting up.
Test it:
sudo reboot
Practical example:
Add this file to your Desktop: test_code.py (run it to check that it works for you)
from os.path import expanduser
import datetime
file = open(expanduser("~") + '/Desktop/HERE.txt', 'w')
file.write("It worked!\n" + str(datetime.datetime.now()))
file.close()
Run the following commands:
sudo cp -i ~/Desktop/test_code.py /bin
sudo crontab -e
Add the following line and save it:
#reboot python /bin/test_code.py &
Now reboot your computer and you should find a new file on your Desktop: HERE.txt
Put this in /etc/init (Use /etc/systemd in Ubuntu 15.x)
mystartupscript.conf
start on runlevel [2345]
stop on runlevel [!2345]
exec /path/to/script.py
By placing this conf file there you hook into ubuntu's upstart service that runs services on startup.
manual starting/stopping is done with
sudo service mystartupscript start
and
sudo service mystartupscript stop
If you are on Ubuntu you don't need to write any other code except your Python file's code , Here are the Steps :-
Open Dash (The First Icon In Sidebar).
Then type Startup Applications and open that app.
Here Click the Add Button on the right.
There fill in the details and in the command area browse for your Python File and click Ok.
Test it by Restarting System . Done . Enjoy !!
Create file ~/.config/autostart/MyScript.desktop
with
[Desktop Entry]
Encoding=UTF-8
Name=MyScript
Comment=MyScript
Icon=gnome-info
Exec=python /home/your_path/script.py
Terminal=false
Type=Application
Categories=
X-GNOME-Autostart-enabled=true
X-GNOME-Autostart-Delay=0
It helps me!
In similar situations, I've done well by putting something like the following into /etc/rc.local:
cd /path/to/my/script
./my_script.py &
cd -
echo `date +%Y-%b-%d_%H:%M:%S` > /tmp/ran_rc_local # check that rc.local ran
This has worked on multiple versions of Fedora and on Ubuntu 14.04 LTS, for both python and perl scripts.
nano /etc/rc.local
and edit in
python ~/path-to-script.py
worked for me

Categories

Resources