One thing I keep having trouble with in Python is passing information from one function to another, changing it and then passing it back to the original function to usefully use. Take a look at this very basic example, trying to create a ping function that can be called by various other functions.
import subprocess
pingchk = 0
def pinger(pcName, pingchk):
ping_out = subprocess.Popen(["ping", "-n", "1", pcName],stdout = subprocess.PIPE).communicate()[0]
if ('unreachable' in ping_out):
print "Warning", "PC not responding 1."
pingchk += 1
return pingchk
elif ('Request timed out.' in ping_out):
print "Warning", "PC not responding 2."
pingchk += 1
print pingchk
return pingchk
elif ('Ping request could not find host' in ping_out):
print "Warning", "PC not responding 3."
pingchk += 2
print pingchk
return pingchk
else:
print "Machine available!"
def someFunction():
pcName = raw_input("Please enter a pc name: ")
pinger(pcName, pingchk)
print pingchk
if pingchk == 1:
print "machine not switched on."
elif pingchk == 2:
print "machine name not recognized."
else:
print "success - machine on."
someFunction()
It's the pingchk
bit that I'm struggling with. In this example someFunction
is passing the machineName
up to pinger
to do the work, then I want pinger
to pass the result back to someFunction
to use. However, someFunction
never re-reads the variable pingchk
so always reads it as 0
.
What do I need to change to pass the results of pinger
back to the originating function for use?