我是python的新手,并不熟悉python语法。我的问题是我正在尝试开发一个应用程序(在控制台上),可以ping不同的(用户定义的)IP和正确ping的ip,所以只需打印"主机可用"但是没有响应的ip生成消息"主机不可用",并且每5分钟自动生成一次。我试图用for循环但不能执行我想要的东西。有人可以帮我解决这个问题吗?
这是我的代码:
import subprocess
import os
import ctypes # An included library with Python install.
import time
with open(os.devnull, "wb") as limbo:
for n in xrange(1,10):
ip="192.168.0.{0}".format(n)
result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
stdout=limbo, stderr=limbo).wait()
if result:
print ip,ctypes.windll.user32.MessageBoxA(0, "Sorry! Host is not Available.", "Alert!", 1)
else:
print ip, "Host Is Available"
print ("IP Monitor!")
time.sleep(5)
import subprocess
import os
import ctypes # An included library with Python install.
import time
with open(os.devnull, "wb") as limbo:
for n in xrange(1,10):
ip="192.168.0.{0}".format(n)
result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
stdout=limbo, stderr=limbo).wait()
if result:
print ip,ctypes.windll.user32.MessageBoxA(0, "Sorry! Host is not Available.", "Alert!", 1)
else:
print ip, "Host Is Available"
input()
答案 0 :(得分:2)
您需要的是在创建communicate()
对象后立即调用Popen
:
from subprocess import Popen, PIPE
def host_is_available(ip):
'''
Pings a host and return True if it is available, False if not.
'''
cmd = ['ping', '-c', '1', '-t', '1', ip]
process = Popen(cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = process.communicate()
return process.returncode == 0 # code=0 means available
ip = '192.168.1.2'
if host_is_available(ip):
print '{} is available'.format(ip)
else:
print '{} is not available'.format(ip)
Popen()
创建一个对象(一个进程),但不执行命令communicate()
communicate()
返回stdout
和stderr
,您可以将其丢弃或使用os.devnull
以放弃输出答案 1 :(得分:1)
为了让某些东西永远运行,你需要一个无限循环,而不是for
循环。
以下是如何运行五次:
for i in (xrange 5):
... do stuff ...
或通常使用适当数量的项目循环:
for personality in ['openness', 'conscientiousness', 'extraversion',
'agreeableness', 'neuroticism']:
... do stuff ...
以下是如何永远做事:
while True:
... do stuff ...
或等效(但不明确)任何真实条件都可以:
while 1 != 0:
... do stuff ...
通常,首先进行初始化,然后运行循环。因此,考虑到@HaiVu的答案,您的整个代码将如下所示:
import subprocess
import os
import ctypes
import time
print ("IP Monitor!")
while True:
for n in xrange(1,10):
ip="192.168.0.{0}".format(n)
process = subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode != 0:
print ip,ctypes.windll.user32.MessageBoxA(0,
"Sorry! Host is not Available.", "Alert!", 1)
else:
print ip, "Host Is Available"
time.sleep(5)
将常规print
与特定于操作系统的消息框混合似乎是错误的(并且我不知道消息框的print
会产生什么;并且如果没有消息框,消息框就没用了IP地址,也许是消息中的时间戳)但希望这至少可以让你开始。