gpt4 book ai didi

Python - Ping 输入的特定 IP

转载 作者:行者123 更新时间:2023-12-01 03:54:19 27 4
gpt4 key购买 nike

我正在尝试 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!'

最佳答案

相关代码存在一些问题,但这里是一个更接近工作版本的版本:

# 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 中,这将帮助您选择使用哪一个。

关于Python - Ping 输入的特定 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37764694/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com