This code pings various machines. Could you please help me change this code so if a process of pinging hangs for more then 7 seconds it shuts down and returns some flag?
(I'd like to pull various data from machines using WMI. For that I'll change ping function to something else. The issue is on some machines WMI is corrupted and process of pulling data hangs indefinitely. Timeout is needed.)
import multiprocessing.dummy import subprocess import numpy as np import time start_time = time.time() def ping(ipadd): try: response = subprocess.check_output(['ping', ipadd]) return True except subprocess.CalledProcessError as e: return False #print(ping('10.25.59.20')) machine_names = \ ''' ya.ru microsoft.com www.google.com www.amazon.com www.nasa.com '''.split() np_machine_names = np.array(machine_names) p = multiprocessing.dummy.Pool(7) ping_status = p.map(ping, machine_names) np_ping_status = np.fromiter(ping_status, dtype=bool) print(*np_machine_names[np_ping_status], sep = '\n') run_time = time.time() - start_time print(f'Runtime: {run_time:.0f}') UPDATE: While I appreciate for the tip on adding timeout to subprocess the question remains. How do I shutdown hanged function? Let's say I've changed pinging to pulling WMI data from a machine (this one pulls list of installed software from Windows machine). There is no subprocess to set timer on:
#pip install pypiwin32 import win32com.client strComputer = "." objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator") objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2") colItems = objSWbemServices.ExecQuery("Select * from Win32_Product") for objItem in colItems: print( "Caption: ", objItem.Caption )
timeoutto yoursubprocess.check_outputcall, i.e.response = subprocess.check_output(['ping', ipadd], timeout=7). Read more onsubprocess.check_outputin the official docs.