本文整理匯總了Python中timeout_decorator.timeout方法的典型用法代碼示例。如果您正苦於以下問題:Python timeout_decorator.timeout方法的具體用法?Python timeout_decorator.timeout怎麽用?Python timeout_decorator.timeout使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類timeout_decorator
的用法示例。
在下文中一共展示了timeout_decorator.timeout方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: poke_tcp_server
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def poke_tcp_server(server_port):
for i in range(4):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.1)
sock.connect(("127.0.0.1", server_port))
try:
sock.send("123".encode(encoding="ascii"))
print ("data sent (P3)")
except (AttributeError, UnicodeDecodeError):
sock.send(bytes("123"))
print ("data sent (P2)")
finally:
sock.close()
print ("socket closed")
except (socket.timeout, socket.error):
time.sleep(0.1)
示例2: connect
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def connect(self):
# this reduces the timeout of SSHClient's connect()
# for failed dns lookups
try:
self.host_check(self.host)
except Exception as e:
# todo logging e
print('[-] CONNECTION FAILED', self.host)
return None
try:
s = SSHClient()
s.set_missing_host_key_policy(AutoAddPolicy())
if self.password:
s.connect(self.host, port=22, username=self.user,
password=self.password, timeout=1)
else:
s.connect(self.host, port=22, username=self.user,
timeout=1, pkey=self.key)
return s
except Exception as e:
# todo logging e
print('[-] CONNECTION FAILED:', self.host)
示例3: WaitForProcessRunning
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def WaitForProcessRunning(self, process, timeout):
"""Blocks until either the timeout passes or the process is running.
Args:
process: string name of the process.
timeout: number of seconds to block while the process is not running.
Raises:
WaitTimeoutError: raised if the process does not run within "timeout"
seconds.
"""
command = ('$count={timeout};'
'while( (ps | select-string {process} | measure-object).Count '
'-eq 0 -and $count -gt 0) {{sleep 1; $count=$count-1}}; '
'if ($count -eq 0) {{echo "FAIL"}}').format(
timeout=timeout, process=process)
stdout, _ = self.RemoteCommand(command)
if 'FAIL' in stdout:
raise WaitTimeoutError()
示例4: measure_power
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def measure_power(self, hz, duration, tag, offset=30):
"""Measure power consumption of the attached device.
Because it takes some time for the device to calm down after the usb
connection is cut, an offset is set for each measurement. The default
is 30s. The total time taken to measure will be (duration + offset).
Args:
hz: Number of samples to take per second.
duration: Number of seconds to take samples for in each step.
offset: The number of seconds of initial data to discard.
tag: A string that's the name of the collected data group.
Returns:
A MonsoonData object with the measured power data.
"""
num = duration * hz
oset = offset * hz
data = None
self.usb("auto")
time.sleep(1)
with self.dut.handle_usb_disconnect():
time.sleep(1)
try:
data = self.take_samples(hz, num, sample_offset=oset)
if not data:
raise MonsoonError(
"No data was collected in measurement %s." % tag)
data.tag = tag
self.dut.log.info("Measurement summary: %s", repr(data))
return data
finally:
self.mon.StopDataCollection()
self.log.info("Finished taking samples, reconnecting to dut.")
self.usb("on")
self.dut.adb.wait_for_device(timeout=DEFAULT_TIMEOUT_USB_ON)
# Wait for device to come back online.
time.sleep(10)
self.dut.log.info("Dut reconnected.")
示例5: ratio_timeout
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def ratio_timeout(self, ratio=0.5):
return timeout_decorator.timeout(
ratio * self.time_budget - (time.time() - self.start_time)
)
示例6: es
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def es():
class Elasticsearch(object):
def __init__(self, url):
verify = default.from_env("PYTHONHTTPSVERIFY") == "1"
self.es = elasticsearch.Elasticsearch(url,
verify_certs=verify,
connection_class=elasticsearch.RequestsHttpConnection)
self.index = "apm-*"
def clean(self):
self.es.indices.delete(self.index)
self.es.indices.refresh()
def term_q(self, filters):
clauses = []
for field, value in filters:
if isinstance(value, list):
clause = {"terms": {field: value}}
else:
clause = {"term": {field: {"value": value}}}
clauses.append(clause)
return {"query": {"bool": {"must": clauses}}}
@timeout_decorator.timeout(10)
def count(self, q):
ct = 0
while ct == 0:
time.sleep(3)
s = self.es.count(index=self.index, body=q)
ct = s['count']
return ct
return Elasticsearch(getElasticsearchURL())
示例7: __init__
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def __init__(self, error):
if isinstance(error, dns.exception.Timeout):
error.kwargs["timeout"] = round(error.kwargs["timeout"], 1)
示例8: _get_mx_hosts
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def _get_mx_hosts(domain, nameservers=None, timeout=2.0):
"""
Queries DNS for a list of Mail Exchange hosts
Args:
domain (str): A domain name
nameservers (list): A list of nameservers to query
(Cloudflare's by default)
Returns:
list: A list of ``OrderedDicts``; each containing a ``preference``
integer and a ``hostname``
Raises:
:exc:`checkdmarc.DNSException`
"""
hosts = []
try:
logging.debug("Checking for MX records on {0}".format(domain))
answers = _query_dns(domain, "MX", nameservers=nameservers,
timeout=timeout)
for record in answers:
record = record.split(" ")
preference = int(record[0])
hostname = record[1].rstrip(".").strip().lower()
hosts.append(OrderedDict(
[("preference", preference), ("hostname", hostname)]))
hosts = sorted(hosts, key=lambda h: (h["preference"], h["hostname"]))
except dns.resolver.NXDOMAIN:
raise DNSException("The domain {0} does not exist".format(domain))
except dns.resolver.NoAnswer:
pass
except Exception as error:
raise DNSException(error)
return hosts
示例9: _get_a_records
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def _get_a_records(domain, nameservers=None, timeout=2.0):
"""
Queries DNS for A and AAAA records
Args:
domain (str): A domain name
nameservers (list): A list of nameservers to query
(Cloudflare's by default)
timeout(float): number of seconds to wait for an answer from DNS
Returns:
list: A sorted list of IPv4 and IPv6 addresses
Raises:
:exc:`checkdmarc.DNSException`
"""
qtypes = ["A", "AAAA"]
addresses = []
for qt in qtypes:
try:
addresses += _query_dns(domain, qt, nameservers=nameservers,
timeout=timeout)
except dns.resolver.NXDOMAIN:
raise DNSException("The domain {0} does not exist".format(domain))
except dns.resolver.NoAnswer:
# Sometimes a domain will only have A or AAAA records, but not both
pass
except Exception as error:
raise DNSException(error)
addresses = sorted(addresses)
return addresses
示例10: _get_txt_records
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def _get_txt_records(domain, nameservers=None, timeout=2.0):
"""
Queries DNS for TXT records
Args:
domain (str): A domain name
nameservers (list): A list of nameservers to query
(Cloudflare's by default)
timeout(float): number of seconds to wait for an answer from DNS
Returns:
list: A list of TXT records
Raises:
:exc:`checkdmarc.DNSException`
"""
try:
records = _query_dns(domain, "TXT", nameservers=nameservers,
timeout=timeout)
except dns.resolver.NXDOMAIN:
raise DNSException("The domain {0} does not exist".format(domain))
except dns.resolver.NoAnswer:
raise DNSException(
"The domain {0} does not have any TXT records".format(domain))
except Exception as error:
raise DNSException(error)
return records
示例11: get_spf_record
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def get_spf_record(domain, nameservers=None, timeout=2.0):
"""
Retrieves and parses an SPF record
Args:
domain (str): A domain name
nameservers (list): A list of nameservers to query
(Cloudflare's by default)
timeout(float): Number of seconds to wait for an answer from DNS
Returns:
OrderedDict: An SPF record parsed by result
Raises:
:exc:`checkdmarc.SPFRecordNotFound`
:exc:`checkdmarc.SPFIncludeLoop`
:exc:`checkdmarc.SPFRedirectLoop`
:exc:`checkdmarc.SPFSyntaxError`
:exc:`checkdmarc.SPFTooManyDNSLookups`
"""
record = query_spf_record(domain, nameservers=nameservers, timeout=timeout)
record = record["record"]
parsed_record = parse_spf_record(record, domain, nameservers=nameservers,
timeout=timeout)
parsed_record["record"] = record
return parsed_record
示例12: get_nameservers
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def get_nameservers(domain, approved_nameservers=None,
nameservers=None, timeout=2.0):
"""
Gets a list of nameservers for a given domain
Args:
domain (str): A domain name
approved_nameservers (list): A list of approved nameserver substrings
nameservers (list): A list of nameservers to qu+ery
(Cloudflare's by default)
timeout(float): number of seconds to wait for an record from DNS
Returns:
Dict: A dictionary with the following keys:
- ``hostnames`` - A list of nameserver hostnames
- ``warnings`` - A list of warnings
"""
logging.debug("Getting NS records on {0}".format(domain))
warnings = []
ns_records = _get_nameservers(domain, nameservers=nameservers,
timeout=timeout)
if approved_nameservers:
approved_nameservers = list(map(lambda h: h.lower(),
approved_nameservers))
for nameserver in ns_records:
if approved_nameservers:
approved = False
for approved_nameserver in approved_nameservers:
if approved_nameserver in nameserver.lower():
approved = True
break
if not approved:
warnings.append("Unapproved nameserver: {0}".format(
nameserver
))
return OrderedDict([("hostnames", ns_records), ("warnings", warnings)])
示例13: test_dnssec
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def test_dnssec(domain, nameservers=None, timeout=2.0):
"""
Check for DNSSEC on the given domain
Args:
domain (str): The domain to check
nameservers (list): A list of nameservers to query
timeout (float): Timeout in seconds
Returns:
bool: DNSSEC status
"""
if nameservers is None:
nameservers = ["1.1.1.1", "1.0.0.1",
"2606:4700:4700::1111", "2606:4700:4700::1001",
]
request = dns.message.make_query(get_base_domain(domain),
dns.rdatatype.NS,
want_dnssec=True)
for nameserver in nameservers:
try:
response = dns.query.udp(request, nameserver, timeout=timeout)
if response is not None:
for record in response.answer:
if record.rdtype == dns.rdatatype.RRSIG:
if response.flags & dns.flags.AD:
return True
except Exception as e:
logging.debug("DNSSEC query error: {0}".format(e))
return False
示例14: build_driver
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def build_driver(use_adb=False, proxy=None, lang=None, timeout=MAX_TIMEOUT, fullscreen=True):
opts = webdriver.ChromeOptions()
#opts.add_argument("load-extension=../misc/jsinj/")
if use_adb:
opts.add_argument("load-extension=../misc/adblocker/unpacked/3.21.0_0/")
if proxy:
opts.add_argument("proxy-server={}".format(proxy))
#opts.add_argument("start-maximized")
if fullscreen:
opts.add_argument("start-fullscreen")
opts.add_argument("disable-infobars") # we remove the ugly yellow notification "Chrome is being controlled by automated test software"
#opts.add_argument("disable-web-security") # We need this to disable SOP and access iframe content
if lang:
#print lang
opts.add_argument("lang={}".format(lang))
driver = webdriver.Chrome(executable_path="/usr/lib/chromium-browser/chromedriver", chrome_options=opts)
if timeout:
driver.set_page_load_timeout(timeout)
return driver
示例15: try_executing_query
# 需要導入模塊: import timeout_decorator [as 別名]
# 或者: from timeout_decorator import timeout [as 別名]
def try_executing_query(prediction, cursor, case_sensitive=True, verbose=False):
"""Attempts to execute a SQL query against a database given a cursor."""
exception_str = None
prediction_str = prediction[:]
prediction_str = prediction_str.replace(';', '').strip()
print('Current prediction:' + prediction_str)
try:
if not case_sensitive:
new_prediction = ''
last_quote = ''
for char in prediction:
new_prediction += char
if char in {'"', '\''} and not last_quote:
last_quote = char
elif char == last_quote:
last_quote = ''
new_prediction += ' COLLATE NOCASE'
prediction = new_prediction
if verbose:
print('Executing case-insensitive query:')
print(new_prediction)
pred_results = timeout_execute(cursor, prediction)
except timeout_decorator.timeout_decorator.TimeoutError:
print('!time out!')
pred_results = []
exception_str = 'timeout'
except (sqlite3.Warning, sqlite3.Error, sqlite3.DatabaseError,
sqlite3.IntegrityError, sqlite3.ProgrammingError,
sqlite3.OperationalError, sqlite3.NotSupportedError) as e:
exception_str = str(e).lower()
pred_results = []
return pred_results, exception_str