[英]Python, wait until network interface is up?
I have a python script which opens a port and listens to it on Raspberry. 我有一个python脚本,它打开一个端口并在Raspberry上监听它。 I added it to /etc/rc.local
and everything is working properly. 我将它添加到/etc/rc.local
,一切正常。 But my problem is the socket which is not created when the process is being executed. 但我的问题是在执行进程时未创建的套接字。
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()
the above code is not executed because there is no 'eth0' connection available. 上述代码未执行,因为没有'eth0'连接可用。 What should I do? 我该怎么办? Should I loop scan the socket status until connection is being available? 我应该循环扫描套接字状态,直到连接可用吗? Is there any other more sophisticated solution? 还有其他更复杂的解决方案吗?
Like this: 像这样:
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,))
so this answer equal to my comment answer. 所以这个答案等于我的评论答案。
accept()
方法会阻塞线程,当没有检测到设备连接服务器时,它会阻塞,表示accept()
之后的代码不会被执行。
I don't know anything about Python but generally speaking of socket programming. 我对Python一无所知,但一般来说就是套接字编程。
When you listen you don't need any host ( s.bind(('',port))
). 当你听的时候你不需要任何主机( s.bind(('',port))
)。
You have to determine a function or an event handler that raises when a connection is established (maybe handle_connect
in Python). 您必须确定在建立连接时引发的函数或事件处理程序(可能是Python中的handle_connect
)。
In the handler function you connect the client on a port other than the port you are currently listening. 在处理程序功能中,您将客户端连接到当前正在侦听的端口以外的端口上。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.