我正在使用:Windows 我正在尝试在 ping IP 地址时创建一个简单的 if
语句
import os
hostname = "192.168.8.8." #example
response = os.system("ping -c 1 " + hostname)
#and then check the response...
if response == 0:
print hostname, 'is down'
else:
print hostname, 'is up'
print response
我对此还很陌生,但无论我输入什么 IP 地址,无论有效与否,它都会说它已启动。
最佳答案
os.system() 返回进程退出值。 0 表示成功。
在您的情况下,它已成功执行,因此返回 0。您所要做的就是从 ping 命令获取完整的输出,然后进行字符串比较以查明该 IP 是否处于事件状态。
您需要使用subprocess's checkoutput method
import subprocess
hostname = "google.com"
batcmd="ping -n 1 " + hostname
result = subprocess.check_output(batcmd, shell=True)
if "Received = 1" in result:
print "Is UP"
else:
print "Is Down"
关于python - 固定 IP 地址时在 Python 中创建简单的 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38191011/