2

I have a Python Script which automatically checks the internet connection and is supposed to restart the wifi connection, if the internet fails.

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.

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? Is there a way to wait for the command to 'return' like a function when it has finished?

Big thanks for your help!

Stefan S.
  • 247
  • 3
  • 9

2 Answers2

1

To answer my own question, I found out that os.system() responds with the process return code. 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')
Stefan S.
  • 247
  • 3
  • 9
0

One way you might do this is to have your syscall block until it completes. 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.