创建接收 IP 或 DNS 名称并对其执行 ping 操作的函数

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

在编写将从命令行 ping IP 或 DNS 名称的 python 脚本时遇到问题。该函数需要 return IP 和 ping 它的时间作为列表。如果无法 ping 通 IP 或 DNS,该函数将 return IP 和 'Not Found' 列在一个列表中。这个脚本还需要一个main函数,在命令行中读入单个IP或DNS名称,调用该函数对其进行ping操作,然后将结果显示为:

IP、TimeToPing(毫秒) 10.1.2.3, 10

这是我目前拥有的:

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()

到目前为止,我收到了一个 TabError,用于缩进该行:header = "IP, TimeToPing (ms)"。这条线应该被推回吗?

您的代码中存在一些语法错误。我肯定会推荐 reading/watching 一些关于正确 python 语法的视频,你很快就会好起来的!

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()