Python,等到网络接口启动?

我有一个
python脚本,它打开一个端口并在Raspberry上监听它.我把它添加到/etc/rc.local

一切正常.但我的问题是在执行进程时未创建的套接字.

s = socket.socket()      
s.bind((host_ip,port)) #e.g. host_ip='192.168.1.32' , port=12345
s.listen(5)
while True:
    c,addr = s.accept()
    c.send('ACK')
    c.close()

上述代码未执行,因为没有’eth0’连接可用.我该怎么办?我应该循环扫描套接字状态,直到连接可用吗?还有其他更复杂的解决方案吗?

最佳答案 像这样:

import urllib2,thread
from time import sleep
import netifaces


class _check:
    def __init__(self):
        self.uri="http://www.google.com"
        self.period = 5
        self.status = False
        self.ifaces()
    def check(self):
        try:
            answ = urllib2.urlopen(self.uri)
            if answ:
                self.status = True
                #Now can run your awesome code !
                print "okay go take a beer"
        except Exception,e : print e

    def timer(self,pass_arg) :
        while True :
            if   self.status != True :
                self.check()
                sleep(self.period)
                print "running"
            elif   self.status == True :
                print "thread ending"
                break
    def ifaces(self):
        for i in netifaces.interfaces() :
            try:
                print i,netifaces.ifaddresses(i)[2]
            except:
                print i, "iface not up !"


check = _check()
thread.start_new_thread(check.timer,(None,))

所以这个答案等于我的评论答案.

点赞