Learning to Use/Create Python Functions
A function is a block of code which you can recycle, this is useful as it saves time.
A basic example of a function is below:
def = is defining the function
status() = is the name of the function, () as it is empty there is no parameters within the function.
The example below starts with :
import subprocess – it is a library module where you can use code to push commands regardless of OS you are using. So if I wanted to ping an IP I could use the subprocess module to allow me to ping.
I have created a function called ‘ping’ and in the function I have a parameter called ‘ip_address’ which will be used to call in the IP addresses called ‘device1’ and ‘device2’.
I create a variable called ‘response’ and within the variable/function the ‘subprocess.run’ is used to execute the pings. So I am asking the script to ping 1 packet hence the ‘-c 1’.
stdout=subprocess.PIPE
captures the output of the ping
command (though it is not used in this code).
Once the ping is done, it will then store the result in the ‘response’ variable.
‘return’ is a keyword in Python which is used in functions to send the value or multiple values to the function. So to return the function it is asking for the ‘response’ function and ‘returncode’ if it is 0 it means success. In a nutshell if you use ‘subprocess.run’ then a return code is needed. and if it is not 0 it is false.
The IP addresses being used to ping is 1.1.1.1 and 12.2.2.2. As the ‘ping’ function (ip_address) is what the IP addresses of 1.1.1.1 and 12.2.2.2 is it calling.