If we want to start the python script when ubuntu get boot, we need configure ubuntu boot script.
Case 1. use ubuntu profile configure
1) create a shell script alex_auto.sh at /etc/profile.d/
#!/bin/sh
cd /home/alextest/
echo "alex boot python from profile"
python profile_auto.py
2) create the profile_auto.py on my home path /home/alextest
#test python
import os
import time
f=open('test.txt','ab+')
i=0
while i<10:
print "alex test"+str(i)
f.write(str(i))
i+=1
time.sleep(1)
f.close()
3) reboot.
That's it? yes. Why?
We can take a look of the /etc/profile :
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).
if [ "${PS1-}" ]; then
if [ "${BASH-}" ] && [ "$BASH" != "/bin/sh" ]; then
# The file bash.bashrc already sets the default PS1.
# PS1='\h:\w\$ '
if [ -f /etc/bash.bashrc ]; then
. /etc/bash.bashrc
fi
else
if [ "`id -u`" -eq 0 ]; then
PS1='# '
else
PS1='$ '
fi
fi
fi
# search /etc/profile.d and run all the shell script under it.
if [ -d /etc/profile.d ]; then
for i in /etc/profile.d/*.sh; do
if [ -r $i ]; then
. $i
fi
done
unset i
fi
We can see /etc/profile will search /etc/profile.d and run all the shell scripts under it.
For this case, when the user login twice, what will happen? run twice.
Where can we find the python log as it's run at boot? /var/log/syslog.
Case 2. Use Ubuntu Init configure
If we just want to make the python script run once, we can't use the profile configure.
1) create the init_setup.sh at /etc/init.d/ and chmod to 755
#!/bin/sh
### BEGIN INIT INFO
# Provides: alex
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop:
# Short-Description: test server
### END INIT INFO
cd /home/alextest/
echo "alex boot init"
python init_auto.py
exit 0
Attention: the ### BEGIN INIT INFO to ### END INIT INFO is needed.
2) create init_auto.py at /home/alextest/
#test python
import os
import time
f=open('init.txt','ab+')
i=0
while i<10:
print "alex init"+str(i)
f.write(str(i))
i+=1
time.sleep(1)
f.close()
3) add init_setup.sh to init
> sudo update-rc.d init_setup.sh defaults 95
4) reboot
Now the init_auto.py will only run once. if it's a server, there will be only one server get start.