Start python script when ubuntu get boot

13 篇文章 0 订阅

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值