# How to improve my auto-reconnection Python script

I need some feedback here. Due to a weird issue on my server system, the network card disconnects from the network regularly. I'll fix this at a later date. But I wanted to know if the below script can be improved.

It's comprised of two files. A python script (autoConnect.py), and a Bash script (checkOnline.sh).

autoConnect.py:

#!/usr/bin/python
from subprocess import call, Popen, PIPE, STDOUT
import time
cmd = './checkOnline.sh'
while True:
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
print time.ctime() + ": Offline"
print "Attempting to reconnect..."
print "Determining network profile..."
cmdTwo = "wicd-cli -ySl | sed -n '2 p' | grep -i paws -c"
pTwo = Popen(cmdTwo, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
print "Network profile is \"1\""
defNum = 1
else:
print "Network profile is \"2\""
defNum = 2
print "Connecting to network..."
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
call("wicd-cli -yn " + defNum + " -c")
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
time.sleep(3)
print "Failed to connect. Trying again..."
print "Success, connected to network!"
else:
print time.ctime() + ": Online"
time.sleep(5)


checkOnline.sh:

#!/bin/bash

(ping -w5 -c3 \$host  > /dev/null 2>&1) && echo "1" || (echo "0" && exit 1)


The former is the main file to be run. checkOnline pings google.com 3 times for 5 seconds, if nothing is returned within 5 seconds, it will return 0. If it gets something, it returns 1 into stdout.

I wanted to know if this can be improved for what I want it to do (check if the network is online, search for networks, connect, repeat). As of right now, I'm away from my server's physical location and am unable to test it on the current system I'm using, but the script should be functional.

• Welcome to Code Review, any code you want reviewed needs to be posted in the question itself. – Winston Ewert Oct 29 '11 at 16:33
• Right. Added that. – dragos240 Oct 29 '11 at 16:59
• Good. The only thing for future reference is that the plain english description of your algorithm isn't really necessary. We are all coders here, we read code. The english is only helpful if your algorithm is incomphrensible, which isn't the case here. – Winston Ewert Oct 29 '11 at 17:30
• Right. Okay, I'll remove that. – dragos240 Oct 29 '11 at 17:32

1. I'd move the contents of the script into a main function and then use the if __name__ == '__main__' boilerplate to start it.