Python - Ping输入的

时间:2016-06-11 14:10:15

标签: python

我尝试ping应用程序运行后输入的特定IP地址。这是我当前的代码,但每次输入IP时都会出现错误,说明语法无效。我已经搜索了其他主题,但它们涉及到同时ping一系列IP。谢谢你的帮助。

def pingComputer():
import os
hostname = input("Enter the ip address: ")
response = os.system("ping -c 1 " + hostname)

if response == 0:
    print hostname, 'is up!'
else:
    print hostname, 'is down!'

2 个答案:

答案 0 :(得分:1)

有问题的代码有几个问题,但这里更接近工作版本:

# put the imports here for better readability.
import os

def pingComputer():
    # you need to indent when you write code for a function
    # you also need to use raw_input in python 2.x because raw_input returns a string
    # where input tries to interpret the input.
    hostname = raw_input("Enter the ip address: ")
    response = os.system("ping -c 1 " + hostname)

    if response == 0:
        print hostname, 'is up!'
    else:
        print hostname, 'is down!'

# you weren't calling your function,
# I added a standard main check which will call your function.
if __name__ == "__main__":
    pingComputer()

您可以在python 2.X中查看raw_inputinput的一些有用资源,它们可以帮助您选择使用哪一种。

答案 1 :(得分:1)

在ping之前将主机名转换为字符串

clients_detail