2016-06-11 112 views
1

我正在嘗試ping應用程序運行後輸入的特定IP地址。這是我當前的代碼,但每次輸入IP時都會出現錯誤,提示語法無效。我已經搜索了其他主題,但它們涉及一次ping一系列IP。謝謝你的幫助。Python - 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!' 
+1

是您的縮進本題正確? – Serdalis

+0

你需要提供確切的錯誤信息 – PyNEwbie

+0

我不認爲有一個用於ping的-c參數,但不是很確定 – PyNEwbie

回答

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

有幾個有用的資源,你可以看看在raw_inputinput在Python 2.X這將幫助您選擇使用哪一個。

1

主機名轉換成字符串前平

def pingComputer(): 

    import os 
    hostname = input("Enter the ip address: ") 
    response = os.system("ping -c 1 " + str(hostname)) 
    if response == 0: 
    print hostname, 'is up!' 
    else: 
    print hostname, 'is down!'