2024-06-11 08:10:08 发布
网友
我有一个通过wmi连接到许多主机的脚本,如下所示:
wmi.WMI(ip, user=username, password=password))
但是,许多主机通常不可用,在允许脚本尝试下一个主机之前,连接需要花费大量时间。你知道吗
我希望能够在尝试连接到远程主机之前测试其可用性,或者能够设置连接超时。你知道吗
你知道吗?你知道吗
当您遇到网络超时时,它的时间会深深地埋藏在windows注册表(网络堆栈)中。你知道吗
对于您的问题,有许多可能的解决方案,我的解决方案是(除了使用多个线程)引入自定义超时(例如,5秒而不是默认的75秒)
有趣的是,Windows powershell wmi对象确实引入了一个开箱即用的超时选项,而python对象则没有。所以解决问题的一种方法是实现自己的超时。在python中,一种方法是:
https://pythonadventures.wordpress.com/2012/12/08/raise-a-timeout-exception-after-x-seconds/
import signal import time def test_request(arg=None): """Your http request.""" time.sleep(2) return arg class Timeout(): """Timeout class using ALARM signal.""" class Timeout(Exception): pass def __init__(self, sec): self.sec = sec def __enter__(self): signal.signal(signal.SIGALRM, self.raise_timeout) signal.alarm(self.sec) def __exit__(self, *args): signal.alarm(0) # disable alarm def raise_timeout(self, *args): raise Timeout.Timeout() def main(): # Run block of code with timeouts try: with Timeout(3): print test_request("Request 1") with Timeout(1): print test_request("Request 2") except Timeout.Timeout: print "Timeout" ############################################################################# if __name__ == "__main__": main()
当您遇到网络超时时,它的时间会深深地埋藏在windows注册表(网络堆栈)中。你知道吗
对于您的问题,有许多可能的解决方案,我的解决方案是(除了使用多个线程)引入自定义超时(例如,5秒而不是默认的75秒)
有趣的是,Windows powershell wmi对象确实引入了一个开箱即用的超时选项,而python对象则没有。所以解决问题的一种方法是实现自己的超时。在python中,一种方法是:
https://pythonadventures.wordpress.com/2012/12/08/raise-a-timeout-exception-after-x-seconds/
相关问题 更多 >
编程相关推荐