简体   繁体   English

使用Python重新启动Raspberry Pi Wifi

[英]Restarting Raspberry Pi Wifi with Python

I have a Python Script which automatically checks the internet connection and is supposed to restart the wifi connection, if the internet fails. 我有一个Python脚本,该脚本会自动检查互联网连接,如果互联网失败,应该重新启动wifi连接。

This is the function that does this: 这是执行此操作的功能:

def RestartWifi():
  print 'Restarting Wifi.'
  os.system('sudo ifdown --force wlan0')
  time.sleep(6)
  os.system('sudo ifup wlan0')

I have added the sleep command to make sure, that there is enough time to disable, before re-enabling the connection. 我添加了sleep命令,以确保在重新启用连接之前有足够的时间来禁用。

However, is there a way to speed this up and somehow enable the wifi as soon as it is disabled? 但是,有没有一种方法可以加快此速度,并以某种方式在禁用无线网络后立即启用它? Also, what would happen if the first command takes longer than 6 seconds? 另外,如果第一个命令花费的时间超过6秒,会发生什么情况? Is there a way to wait for the command to 'return' like a function when it has finished? 有没有一种方法可以等待命令完成后像函数一样“返回”?

Big thanks for your help! 非常感谢您的帮助!

One way you might do this is to have your syscall block until it completes. 一种可能的方法是让syscall块直到完成。 That way you would not need to wait any more than strictly necessary. 这样一来,您无需等待的时间就比完全必要的多。 One way ensure the call blocks is with the 一种方法是确保呼叫阻止与

subprocess.check_output()

command. 命令。

To answer my own question, I found out that os.system() responds with the process return code. 为了回答我自己的问题, 我发现 os.system()使用进程返回代码进行响应。 This does suggest, that the function only returns after the called sub-process has finished. 这确实表明,该函数仅在被调用的子进程完成后才返回。

Therefore the problem I was trying to solve, seems not to be a problem at all and I should be able to remove the sleep periods. 因此,我试图解决的问题似乎根本不是问题,我应该可以消除睡眠时间。

It does however make sense to have a (very) short delay, just as a precaution and "to let things settle", so to speak. 但是,可以说(非常)短暂的延迟是有意义的,就像预防措施和“让事情安定下来”一样。 In most cases, this one second should't be a problem anyhow. 在大多数情况下,无论如何,这一秒钟都不是问题。

def RestartWifi():
  os.system('sudo ifdown --force wlan0')
  time.sleep(1)
  os.system('sudo ifup wlan0')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM