问题
So I have a python script with which I would like to do at least one of these two things:
- Have it automatically run on boot/log in
- Create a shortcut which runs the script
I have tried every method I could find to do each of these, but it seems the problem is more or less the same each time. Initially it looks as if the program is running, indicated by a big surge in processor activity but this only lasts for a few seconds before the pi goes back to doing nothing. If a terminal opens it shows no message whatsoever. The script opens a pygame window and sometimes (depending on the method used) this window will show up for a few seconds before closing itself.
The script is fairly compicated in that it makes use of images and modules from its directory as well as the GPIO pins.
If I try to run the script from the terminal window it only works properly if I cd into its directory, otherwise it simply says it cannot import an image and hangs. (sudo doesn't seem to make any difference as to whether or not it works)
I'm assuming this means it would work if I managed to get the rpi to move into the script's directory before running it, however I'm not sure if this is possible through shortcuts or any "autostart" method
Hopefully this is all clear if not let me know
回答1:
You must write easy script to run your code like this one :
For example create directory in /opt :
cd /opt
mkdir my_bootup_script
cd my_bootup_script
nano my_python_script.py
Then write python code. For this example i tried this :
#!/usr/bin/python
import sys
import Adafruit_DHT
humidity, temperature = Adafruit_DHT.read_retry(11, 4)
if humidity is not None and temperature is not None:
print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)
else:
print 'Failed to get reading. Try again!'
Then make in same folder bash script for example :
touch my_script_runner.sh
chmod a+x my_script_runner.sh
nano my_script_runner.sh
Then write bash script. For this example i tried this :
#!/bin/bash
cd /opt/my_bootup_script
sudo /usr/bin/python ./my_python_script.py
exit
Try if it is working well : ./my_script_runner.sh
If yes add this script as boot script :
sudo nano /etc/rc.local
# Add Line :
nohup sudo /opt/my_bootup_script/my_script_runner.sh >> /opt/my_bootup_script/my_script_run.log
# Save with ctrl + x and y
Restart R-Pi : sudo reboot and look into folder /opt/my_bootup_script/ for my_script_run.log generated by bootup script for information. This example worked well on my R-Pi. Python script use Adafruit module with Temperature And Humidity Sensor DHT11 on 4th GPIO Pin.
来源:https://stackoverflow.com/questions/30322978/cannot-get-my-python-script-to-run-on-startup-from-a-shortcut-on-raspberry-pi