本文整理汇总了Python中humanfriendly.Timer方法的典型用法代码示例。如果您正苦于以下问题:Python humanfriendly.Timer方法的具体用法?Python humanfriendly.Timer怎么用?Python humanfriendly.Timer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类humanfriendly
的用法示例。
在下文中一共展示了humanfriendly.Timer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: wait_until_connected
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def wait_until_connected(self):
"""
Wait until connections are being accepted.
:raises: :exc:`TimeoutError` when the SSH server isn't fast enough to
initialize.
"""
timer = Timer()
with Spinner(timer=timer) as spinner:
while not self.is_connected:
if timer.elapsed_time > self.wait_timeout:
raise TimeoutError(format(
"Failed to establish connection to %s within configured timeout of %s!",
self.endpoint, format_timespan(self.wait_timeout),
))
spinner.step(label="Waiting for %s to accept connections" % self.endpoint)
spinner.sleep()
logger.debug("Waited %s for %s to accept connections.", timer, self.endpoint)
示例2: run_command
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def run_command(arguments, timeout=None):
"""
Run the specified command (with an optional timeout).
:param arguments: The command line for the external command (a list of
strings).
:param timeout: The optional command timeout (a number or :data:`None`).
:raises: :exc:`CommandTimedOut` if the command times out.
"""
timer = Timer()
logger.info("Running command: %s", quote(arguments))
with execute(*arguments, asynchronous=True) as command:
# Wait for the command to finish or exceed the given timeout.
while command.is_running:
if timeout and timer.elapsed_time > timeout:
raise CommandTimedOut(command, timeout)
# Sleep between 0.1 and 1 second, waiting for
# the external command to finish its execution.
time_to_sleep = min(1, max(0.1, timeout - timer.elapsed_time))
if time_to_sleep > 0:
time.sleep(time_to_sleep)
if command.succeeded:
logger.info("Command completed successfully in %s.", timer)
示例3: __call__
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def __call__(self, name, log_func=None):
"""
Example.
timer = Timer(log)
with timer("Some Routines"):
routine1()
routine2()
"""
if log_func is None:
log_func = self.log.info
start = time.clock()
yield
end = time.clock()
duration = end - start
readable_duration = format_timespan(duration)
log_func(f"{name} :: {readable_duration}")
示例4: test_notifications
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def test_notifications(self):
"""Test the desktop notification functionality."""
timer = Timer()
program = RsyncSystemBackup(destination='/backups/system')
# The happy path.
with MockedProgram('notify-send', returncode=0):
program.notify_starting()
program.notify_finished(timer)
program.notify_failed(timer)
# The sad path (should not raise exceptions).
with MockedProgram('notify-send', returncode=1):
program.notify_starting()
program.notify_finished(timer)
program.notify_failed(timer)
示例5: execute_helper
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def execute_helper(self):
"""Helper for :func:`execute()`."""
timer = Timer()
actions = []
if self.crypto_device and not self.crypto_device_available:
msg = "Encrypted filesystem %s isn't available! (the device file %s doesn't exist)"
raise MissingBackupDiskError(msg % (self.crypto_device, self.crypttab_entry.source_device))
if self.backup_enabled:
self.notify_starting()
self.unlock_device()
try:
self.mount_filesystem()
if self.backup_enabled:
self.transfer_changes()
actions.append('create backup')
if self.snapshot_enabled:
self.create_snapshot()
actions.append('create snapshot')
if self.rotate_enabled:
self.rotate_snapshots()
actions.append('rotate old snapshots')
except Exception:
self.notify_failed(timer)
raise
else:
if self.backup_enabled:
self.notify_finished(timer)
if actions:
logger.info("Took %s to %s.", timer, concatenate(actions))
示例6: create_snapshot
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def create_snapshot(self):
"""
Create a snapshot of the destination directory.
:raises: The following exceptions can be raised:
- :exc:`.DestinationContextUnavailable`, refer
to :attr:`destination_context` for details.
- :exc:`.ParentDirectoryUnavailable`, refer
to :attr:`.parent_directory` for details.
- :exc:`~executor.ExternalCommandFailed` when
the ``cp`` command reports an error.
"""
# Compose the `cp' command needed to create a snapshot.
snapshot = os.path.join(self.destination.parent_directory,
time.strftime('%Y-%m-%d %H:%M:%S'))
cp_command = [
'cp', '--archive', '--link',
self.destination.directory,
snapshot,
]
# Execute the `cp' command?
if self.dry_run:
logger.info("Snapshot command: %s", quote(cp_command))
else:
timer = Timer()
logger.info("Creating snapshot: %s", snapshot)
self.destination_context.execute(*cp_command, ionice=self.ionice)
logger.info("Took %s to create snapshot.", timer)
示例7: test_graceful_to_forceful_fallback
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def test_graceful_to_forceful_fallback(self):
"""Test that graceful termination falls back to forceful termination."""
timer = Timer()
expected_lifetime = 60
with NonGracefulCommand('sleep', str(expected_lifetime), check=False) as cmd:
# Request graceful termination even though we know it will fail.
cmd.terminate(timeout=1)
# Verify that the process terminated even though our graceful
# termination request was ignored.
assert not cmd.is_running
# Verify that the process actually terminated due to the fall back
# and not because its expected life time simply ran out.
assert timer.elapsed_time < expected_lifetime
示例8: check_termination
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def check_termination(self, method):
"""Helper method for process termination tests."""
with ExternalCommand('sleep', '60', check=False) as cmd:
timer = Timer()
# We use a positive but very low timeout so that all of the code
# involved gets a chance to run, but without slowing us down.
getattr(cmd, method)(timeout=0.1)
# Gotcha: Call wait() so that the process (our own subprocess) is
# reclaimed because until we do so proc.is_running will be True!
cmd.wait()
# Now we can verify our assertions.
assert not cmd.is_running, "Child still running despite graceful termination request!"
assert timer.elapsed_time < 10, "It look too long to terminate the child!"
示例9: test_command_pool
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def test_command_pool(self):
"""Make sure command pools actually run multiple commands in parallel."""
num_commands = 10
sleep_time = 4
pool = CommandPool(5)
for i in range(num_commands):
pool.add(ExternalCommand('sleep %i' % sleep_time))
timer = Timer()
results = pool.run()
assert all(cmd.returncode == 0 for cmd in results.values())
assert timer.elapsed_time < (num_commands * sleep_time)
示例10: test_cli_fudge_factor
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def test_cli_fudge_factor(self, fudge_factor=5):
"""Try to ensure that the fudge factor applies (a bit tricky to get right) ..."""
def fudge_factor_hammer():
timer = Timer()
returncode, output = run_cli(
main,
'--fudge-factor=%i' % fudge_factor,
*python_golf('import sys', 'sys.exit(0)')
)
assert returncode == 0
assert timer.elapsed_time > (fudge_factor / 2.0)
retry(fudge_factor_hammer, 60)
示例11: test_cli_timeout
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def test_cli_timeout(self):
"""Ensure that external commands can be timed out."""
def timeout_hammer():
timer = Timer()
returncode, output = run_cli(
main, '--timeout=5',
*python_golf('import time', 'time.sleep(10)')
)
assert returncode != 0
assert timer.elapsed_time < 10
retry(timeout_hammer, 60)
示例12: port_number
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def port_number(self):
"""A dynamically selected free ephemeral port number (an integer between 49152 and 65535)."""
timer = Timer()
logger.debug("Looking for free ephemeral port number ..")
for i in itertools.count(1):
value = self.ephemeral_port_number
set_property(self, 'port_number', value)
if not self.is_connected:
logger.debug("Found free ephemeral port number %s after %s (took %s).",
value, pluralize(i, "attempt"), timer)
return value
示例13: apply_fudge_factor
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def apply_fudge_factor(fudge_factor):
"""
Apply the requested scheduling fudge factor.
:param fudge_factor: The maximum number of seconds to sleep (a number).
Previous implementations of the fudge factor interrupt used UNIX signals
(specifically ``SIGUSR1``) but the use of this signal turned out to be
sensitive to awkward race conditions and it wasn't very cross platform, so
now the creation of a regular file is used to interrupt the fudge factor.
"""
if fudge_factor:
timer = Timer()
logger.debug("Calculating fudge factor based on user defined maximum (%s) ..",
format_timespan(fudge_factor))
fudged_sleep_time = fudge_factor * random.random()
logger.info("Sleeping for %s because of user defined fudge factor ..",
format_timespan(fudged_sleep_time))
interrupt_file = get_lock_path(INTERRUPT_FILE)
while timer.elapsed_time < fudged_sleep_time:
if os.path.isfile(interrupt_file):
logger.info("Fudge factor sleep was interrupted! (%s exists)",
interrupt_file)
break
time_to_sleep = min(1, fudged_sleep_time - timer.elapsed_time)
if time_to_sleep > 0:
time.sleep(time_to_sleep)
else:
logger.info("Finished sleeping because of fudge factor (took %s).", timer)
示例14: generate_key_file
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def generate_key_file(self, filename):
"""
Generate a temporary host or client key for the OpenSSH server.
The :func:`start()` method automatically calls :func:`generate_key_file()`
to generate :data:`host_key_file` and :attr:`client_key_file`. This
method uses the ``ssh-keygen`` program to generate the keys.
"""
if not os.path.isfile(filename):
timer = Timer()
self.logger.debug("Generating SSH key file (%s) ..", filename)
execute('ssh-keygen', '-f', filename, '-N', '', '-t', 'rsa', silent=True, logger=self.logger)
self.logger.debug("Generated key file %s in %s.", filename, timer)
示例15: timer
# 需要导入模块: import humanfriendly [as 别名]
# 或者: from humanfriendly import Timer [as 别名]
def timer(name):
st = time.time()
yield
print("<Timer> {} : {}".format(name, format_timespan(time.time() - st)))