Good day. I am using a Raspberry Pi 3 model B running Raspbian Stretch. I have a Python script named bluepyscanner.py which is basically a Python 3 variation of the bluepy scanner sample code with a small addition for a .txt log file.
from bluepy.btle import Scanner, DefaultDelegate
class ScanDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)
def handleDiscovery(self, dev, isNewDev, isNewData):
if isNewDev:
print("Discovered device", dev.addr)
elif isNewData:
print("Received new data from", dev.addr)
scanner = Scanner().withDelegate(ScanDelegate())
devices = scanner.scan(10.0)
for dev in devices:
print("Device {} ({}), RSSI={} dB".format(dev.addr, dev.addrType, dev.rssi))
for (adtype, desc, value) in dev.getScanData():
print(" {} = {}".format(desc, value))
with open('bluepyscanlog.txt', 'a') as the_file:
the_file.write("{}={}\n".format(desc, value))
I can run this script perfectly when I launch it from terminal with
$ sudo python3 /home/pi/bluepyscanner.py
However, I am somehow unable to get this script to run automatically on boot. I have tried the following three methods separately and none has worked so far:
rc.local (https://www.raspberrypi.org/documentation/linux/usage/rc-local.md): I appended the following line to /etc/rc.local
python3 /home/pi/bluepyscanner.py
Cron (https://www.raspberrypi.org/documentation/linux/usage/cron.md): I used the Cron GUI and added a recurring task to be launched "at reboot"
sudo python3 /home/pi/bluepyscanner.py
systemd (https://www.raspberrypi.org/documentation/linux/usage/systemd.md): I followed the instructions on the linked documentation page with main.py replaced by my bluepyscanner.py and the working directory replaced by /home/pi
Can anyone give me a pointer on what might have gone wrong? Bluetooth is enabled and bluepy is installed in accordance with this. I don't think the script has run because, unlike when ran from terminal, bluepyscanlog.txt was not created.
Thank you in advance for your time.
Please make these changes into your script
...
with open('/home/pi/bluepyscanlog.txt', 'a+') as the_file:
...
and make the proper changes in your /etc/rc.local
sudo python3 /home/pi/bluepyscanner.py
May be you can see previous copies of bluepyscanlog.txt at /
If this doesn't do the job bluetooth service may be starting after rc.local is executed. Do this modifications in your /etc/rd.local as sudo
....
sudo service bluetooth start
sudo python3 /home/pi/bluepyscanner.py > /home/pi/bb.log
exit 0
Ensure that exit 0 is the last command in the file. If you created rc.local manually ensure it gets execution rights.
sudo chmod +x /etc/rc.local
You will see that your script is being executed.
In my raspberry these are the contents of bb.log
Discovered device d2:xx:XX:XX:XX:XX
Device d2:xx:XX:XX:XX:XX (random), RSSI=-62 dB
Flags = 06
0x12 = 08001000
Incomplete 128b Services = xxxxxxxxxxxxxxxxxxxxxxxxx
16b Service Data = xxxxxxxxxxxxxx
Complete Local Name = xxxxxxxxxxx
Tx Power = 05
(Xs mask original content)
Related
I am running Raspbian on a Raspberry Pi. I have a python script set in /etc/rc.local to run when the device is booted. The python script was working as expected until I added mysql functionality to the script. Mysql is correctly installed and configured; the mysql functionality in the script works as expected when run manually from the shell. According to /var/log/syslog, the script is unable to find the mysql module:
Mar 17 10:18:42 PressPi rc.local[464]: Traceback (most recent call last):
Mar 17 10:18:42 PressPi rc.local[464]: File "/home/pi/python/switch_counter3.py", line 20, in <module>
Mar 17 10:18:42 PressPi rc.local[464]: import mysql.connector
Mar 17 10:18:42 PressPi rc.local[464]: ModuleNotFoundError: No module named 'mysql'
Python import statement :
import mysql.connector
/etc/rc.local entry :
python3 /home/pi/python/switch_counter3.py &
I also tried :
sudo python3 /home/pi/python/switch_counter3.py &
I tried to add a 60 second sleep in rc.local before the python script was called, in case the script was running before mysql was initialized. I can see in syslog that the script is waiting the 60 seconds before running, but I get the same error message.
I could try other methods to automate the script, but I am interested in why the current method is not working as expected.
As Tim Roberts helped me learn, the rc.local script was running as root, but I had installed mysql under my user account. Running from rc.local, the script couldn't find the mysql package. I added sudo -H -u username when calling the python script in /etc/rc.local, and the script runs as expected.
Thank you to Tim Roberts.
for those interested in the full /etc/rc.local. Everything before the sleep statement was default.
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.
# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
printf "My IP address is %s\n" "$_IP"
fi
#make sure mysql has been initialized
sleep 15
#run python script as user pi with python3
#The ampersand allows the command to run in a separate process and continue booting with the process running.
sudo -H -u pi python3 /home/pi/python/switch_counter3.py &
exit 0
I created a python program, "test.py" and have saved it under /home/pi/. When I go to run it in the terminal using "python3 /home/pi/test.py" it runs properly and speaks "hello world". The code is shown below.
import os
import alsaaudio
m = alsaaudio.Mixer()
current_volume = m.getvolume()
m.setvolume(35)
os.system("espeak 'Hello World!'")
I want this program to start whenever my raspberry pi starts up. I tried to add this line in crontab but my raspberry pi doesn't execute the command. Does anyone know why my program won't execute?
#reboot python3 /home/pi/test.py
Here is an image of the syslog
can you try adding the full path to python3:
#reboot /usr/bin/python3 /home/pi/test.py
Also, regarding wanting to run the code on when the device boots - you can run your code as a service.
To do so create a .service file under /etc/systemd/system (for example my-code.service)
Enter the following inside the file
[Unit]
Description=My python service
After=network.target
[Service]
ExecStart=/usr/bin/python3 -u test.py
WorkingDirectory=/home/pi
[Install]
WantedBy=multi-user.target
Finally enable the service (in order for it to run on boot)
sudo systemctl enable my-code
If you want to run it independently you can also run
sudo systemctl start my-code
I need to run a deamon over a remote Linux machine, using SSH.
Deamon's name is pigpiod and it belongs to pigpio module ( controling Raspberry Pi's GPIO ), Ubuntu Mate 16.04.
Executing commands that does not require sudo (for example- ls)- script runs OK, while those who need sudo, fails.
adress='192.168.2.112' , is a remote Linux to run this daemon.
Code below fails (running sudo pigpiod):
def runpigpiod_remote(adress):
result = subprocess.run(['ssh','guy#'+adress,'sudo','pigpiod'])
Code below succeeds(run ls -l)
def runpigpiod_remote(adress):
result = subprocess.run(['ssh','guy#'+adress,'ls','-l'])
In order the check if subprocess.run capable of executing sudo+ command - I tryied localy on same machine and it succeeds:
def run_process():
try:
check_output(["pidof","pigpiod"])
print("pigpiod already loaded")
except:
subprocess.CalledProcessError
print("Not Loaded")
subprocess.run(['sudo','pigpiod'])
if os.system("pgrep -x "+name)==0:
print("Loaded successfully")
Code changed ( thanks to comment of #Hamuel )- as noted in proper way to sudo over ssh
def runpigpiod_remote(adress):
result = subprocess.run(['ssh','-t','guy#'+adress,'sudo','pigpiod'])
In installed Sleepwatcher 2.2 on OS X 10.11 and launching it via LaunchD as an agent.
It launches okay and shows up in the activity monitor.
However, I want it to fire off a python script when the computer wakes up.
My installation commands are as follows.
sudo mkdir -p /usr/local/sbin /usr/local/share/man/man8
sudo cp ~/Desktop/sleepwatcher_2.2/sleepwatcher /usr/local/sbin
sudo cp ~/Desktop/sleepwatcher_2.2/sleepwatcher.8 /usr/local/share/man/man8
sudo cp ~/Desktop/sleepwatcher_2.2/sleepwatcher/config/rc.sleep /etc
sudo cp ~/Desktop/sleepwatcher_2.2/sleepwatcher/config/rc.wakeup /etc
sudo cp ~/Desktop/sleepwatcher_2.2/sleepwatcher/config/de.bernhard-baehr.sleepwatcher-20compatibility-localuser.plist /Library/LaunchAgents
chmod +x /etc/rc.sleep
chmod +x /etc/rc.wakeup
chmod +x /usr/local/bin/test.py
My rc.wakeup file is as follows.
#!/bin/sh
/usr/local/bin/python3 /usr/local/bin/test.py
When executing Sleepwatcher at the terimnal window by typing in the following, it seems to work.
/usr/local/sbin/sleepwatcher --verbose --wakeup /usr/local/bin/test.py
However, when trying to run it as a start-up item under LaunchD, it does not seem to work execute my python script.
I have search all over and cannot figure out why it is not working when being launched in LaunchD.
Has anybody ran into this type of problem?
Thanks in advance.
I encountered similar problems so I took a different approach using another open source tool called Hammerspoon. It can provide for automation of bunch of things on MacOS including sleep/wake events. It's quite simple to replicate sleepwatcher's functionality by adding the following to Hammerspoon's ~/.hammerspoon/init.lua (or create a 'spoon') script that triggers when the machine wakes or sleeps and calls the corresponding wake and sleep scripts (in e.g. /Users/username/scripts - ensure username is changed) from sleepwatcher:
function caffeinateWatcher(eventType)
if (eventType == hs.caffeinate.watcher.systemWillSleep or
eventType == hs.caffeinate.watcher.systemWillPowerOff) then
print ("WillSleep...")
-- Execute sleep script
hs.task.new("/Users/username/scripts/rc.sleep", nil):start()
elseif (eventType == hs.caffeinate.watcher.systemDidWake) then
print ("Woken...")
-- Execute wake script
hs.task.new("/Users/username/scripts/rc.wake", nil):start()
end
end
sleepWatcher = hs.caffeinate.watcher.new(caffeinateWatcher)
sleepWatcher:start()
Note if you want Hammerspoon to launch the shell scripts you need to ensure they start with the standard bash shell header #!/bin/bash.
I'm using python fabric to deploy binaries to an ec2 server and am attempting to run them in background (a subshell).
All the fabric commands for performing local actions, putting files, and executing remote commands w/o elevated privileges work fine. The issue I run into is when I attempt to run the binary.
with cd("deploy"):
run('mkdir log')
sudo('iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080', user="root")
result = sudo('./dbserver &', user="root") # <---- This line
print result
if result.failed:
print "Running dbserver failed"
else:
print "DBServer now running server" # this gets printed despite the binary not running
After I login to the server and ps aux | grep dbserver nothing shows up. How can I get fabric to execute the binary? The same command ./dbserver & executed from the shell does exactly what I want it to. Thanks.
This is likey reated to TTY issues, and/or that you're attempting to background a process.
Both of these are discussed in the FAQ under these two headings:
http://www.fabfile.org/faq.html#init-scripts-don-t-work
http://www.fabfile.org/faq.html#why-can-t-i-run-programs-in-the-background-with-it-makes-fabric-hang
Try making the sudo like this:
sudo('nohup ./dbserver &', user=root, pty=False)