Python 脚本 运行 当我把它放在 /etc/network/if-up.d/ 时多次?
Python script running multiple times when I put it in /etc/network/if-up.d/?
我制作了一个 python 脚本,它使用 SMTP 服务器将邮件发送到给定的 ID。我希望每次连接到互联网时脚本都 运行,所以我把我的文件(比如 python.py) 在位置 "/etc/network/if-up.d/" 中没有扩展名,并使其可由 "sudo chmod +x /etc/network/if-up.d/python" 命令执行。一切正常,即我的脚本 运行 当我连接到互联网时,但后来我注意到邮件发送到的电子邮件 ID 收到多封邮件(大部分是两次),这意味着脚本 运行 多次。为什么会这样?脚本是否在 "if-up.d/" 运行 多次保存或与我的网络有关。(注意:我的网络(usb-tethered)在此过程中没有断开连接,我使用了类似的使用 crontab 启动后 运行 的脚本,它 运行 很好。我正在使用 Ubutu 16.04)
这是一个老问题,但我 运行 遇到了类似的问题。我的post可以查看here但是如果-up.d/没有gua运行tee一个脚本只会运行一次。它所做的是获取脚本并在每个接口的基础上执行它([=12= 执行一次,wlan0
执行一次,lo
执行一次,等等)。如果脚本只需要 运行 一次,那么获得所需效果的两个选项是:
我的初步做法
在脚本级别,如果您 运行ning 是连续的,您可以检查以确保只有一个脚本实例是 运行ning。我正在 运行 为我们的 IRC 服务器连接一个 python 机器人,因此连接了两次,我写了这个来解决它
def check_running():
get_processes = 'ps aux'.split() # grab list of running processes
get_bots = 'grep bot.py$ -c'.split() # search for your script, note the '$' for an end of line match and '-c' for a numeric count of occurrences
out1 = subprocess.Popen(get_processes, stdout=subprocess.PIPE)
out2 = int(subprocess.check_output(get_bots, stdin=out1.stdout).rstrip())
return out2
if check_running() != 1: # the count should be one since the script is looking for itself
sys.exit(0)
# continue with the script after performing initial check
准确的方法
我将对 python 的调用包装在一个 sh 脚本中,sh 脚本就是存储在 if-up.d/
中的内容。对于这种方法,我需要做的就是更新我的脚本以在执行调用之前验证我想使用的界面。
[ "$IFACE" = 'eth0' ] || exit 0 # interface accessing script must match, or exit
sleep 269
sh -c "python /dir/to/bot.py >> /dir/to/log" & disown
我制作了一个 python 脚本,它使用 SMTP 服务器将邮件发送到给定的 ID。我希望每次连接到互联网时脚本都 运行,所以我把我的文件(比如 python.py) 在位置 "/etc/network/if-up.d/" 中没有扩展名,并使其可由 "sudo chmod +x /etc/network/if-up.d/python" 命令执行。一切正常,即我的脚本 运行 当我连接到互联网时,但后来我注意到邮件发送到的电子邮件 ID 收到多封邮件(大部分是两次),这意味着脚本 运行 多次。为什么会这样?脚本是否在 "if-up.d/" 运行 多次保存或与我的网络有关。(注意:我的网络(usb-tethered)在此过程中没有断开连接,我使用了类似的使用 crontab 启动后 运行 的脚本,它 运行 很好。我正在使用 Ubutu 16.04)
这是一个老问题,但我 运行 遇到了类似的问题。我的post可以查看here但是如果-up.d/没有gua运行tee一个脚本只会运行一次。它所做的是获取脚本并在每个接口的基础上执行它([=12= 执行一次,wlan0
执行一次,lo
执行一次,等等)。如果脚本只需要 运行 一次,那么获得所需效果的两个选项是:
我的初步做法
在脚本级别,如果您 运行ning 是连续的,您可以检查以确保只有一个脚本实例是 运行ning。我正在 运行 为我们的 IRC 服务器连接一个 python 机器人,因此连接了两次,我写了这个来解决它
def check_running():
get_processes = 'ps aux'.split() # grab list of running processes
get_bots = 'grep bot.py$ -c'.split() # search for your script, note the '$' for an end of line match and '-c' for a numeric count of occurrences
out1 = subprocess.Popen(get_processes, stdout=subprocess.PIPE)
out2 = int(subprocess.check_output(get_bots, stdin=out1.stdout).rstrip())
return out2
if check_running() != 1: # the count should be one since the script is looking for itself
sys.exit(0)
# continue with the script after performing initial check
准确的方法
我将对 python 的调用包装在一个 sh 脚本中,sh 脚本就是存储在 if-up.d/
中的内容。对于这种方法,我需要做的就是更新我的脚本以在执行调用之前验证我想使用的界面。
[ "$IFACE" = 'eth0' ] || exit 0 # interface accessing script must match, or exit
sleep 269
sh -c "python /dir/to/bot.py >> /dir/to/log" & disown