'Create function that takes in IP or DNS name and pings it

Having trouble writing a python script that will ping an IP or DNS name from the command line. The function needs to return the IP and the time to ping it as a list. If the IP or DNS cannot be pinged, the function will return the IP and 'Not Found' in a list. This script also needs a main function that reads in a single IP or DNS name on the command line, calls the function to ping it, and then displays the result as:

IP, TimeToPing (ms) 10.1.2.3, 10

This is what I have so far:

import ipaddress
import subprocess
from pythonping import ping

    #Main routine
    def main():
        try:
            address = sys.argv([1])
            pingthis = ping(address)
            header = "IP, TimeToPing (ms)"
    
    
    # Run main() if script called directly
    if __name__ == "__main__":
            main()

So far, I'm getting an TabError for indentation for the line: header = "IP, TimeToPing (ms)". Is this line suppose to be pushed back?



Solution 1:[1]

A few syntax errors in your code. I would definitely recommend reading/watching some videos on correct python syntax and you'll be good in no time!

import ipaddress
import subprocess
from pythonping import ping

# unindent everything below like this

#Main routine
def main():
    try:
        address = sys.argv([1])
        pingthis = ping(address)
        header = "IP, TimeToPing (ms)"
    except SomeSpecificException:
        # every try statement must have an except, otherwise, whats the point?
        # code that only runs when the exception is caught

# Run main() if script called directly
if __name__ == "__main__":
    # your line below was 4 spaces over-indented
    main()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 notoriousjere