desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Construct a ReplayPool. Arguments: observation_shape - tuple indicating the shape of the observation action_dim - dimension of the action size - capacity of the replay pool observation_dtype - ... action_dtype - ... concat_observations - whether to concat the past few observations as a single one, so as to ensure the ...
def __init__(self, observation_shape, action_dim, max_steps, observation_dtype=np.float32, action_dtype=np.float32, concat_observations=False, concat_length=1, rng=None):
self.observation_shape = observation_shape self.action_dim = action_dim self.max_steps = max_steps self.observations = np.zeros(((max_steps,) + observation_shape), dtype=observation_dtype) self.actions = np.zeros((max_steps, action_dim), dtype=action_dtype) self.rewards = np.zeros((max_steps,), ...
'Add a time step record. Arguments: observation -- current or observation action -- action chosen by the agent reward -- reward received after taking the action terminal -- boolean indicating whether the episode ended after this time step'
def add_sample(self, observation, action, reward, terminal, extra=None):
self.observations[self.top] = observation self.actions[self.top] = action self.rewards[self.top] = reward self.terminals[self.top] = terminal if (extra is not None): if (self.extras is None): assert (self.size == 0), 'extra must be consistent' self.extras = n...
'Return an approximate count of stored state transitions.'
def __len__(self):
return max(0, (self.size - self.concat_length))
'Return the most recent sample (concatenated observations if needed).'
def last_concat_state(self):
if self.concat_observations: indexes = np.arange((self.top - self.concat_length), self.top) return self.observations.take(indexes, axis=0, mode='wrap') else: return self.observations[(self.top - 1)]
'Return a concatenated state, using the last concat_length - 1, plus state.'
def concat_state(self, state):
if self.concat_observations: indexes = np.arange(((self.top - self.concat_length) + 1), self.top) concat_state = np.empty(((self.concat_length,) + self.observation_shape), dtype=floatX) concat_state[0:(self.concat_length - 1)] = self.observations.take(indexes, axis=0, mode='wrap') co...
'Return corresponding observations, actions, rewards, terminal status, and next_observations for batch_size randomly chosen state transitions.'
def random_batch(self, batch_size):
observations = np.zeros(((batch_size, self.concat_length) + self.observation_shape), dtype=self.observation_dtype) actions = np.zeros((batch_size, self.action_dim), dtype=self.action_dtype) rewards = np.zeros((batch_size,), dtype=floatX) terminals = np.zeros((batch_size,), dtype='bool') if (self.ext...
':param n_itr: Number of iterations. :param max_path_length: Maximum length of a single rollout. :param batch_size: # of samples from trajs from param distribution, when this is set, n_samples is ignored :param discount: Discount. :param plot: Plot evaluation run after each iteration. :param init_std: Initial std for p...
def __init__(self, env, policy, n_itr=500, max_path_length=500, discount=0.99, init_std=1.0, n_samples=100, batch_size=None, best_frac=0.05, extra_std=1.0, extra_decay_time=100, plot=False, n_evals=1, **kwargs):
Serializable.quick_init(self, locals()) self.env = env self.policy = policy self.batch_size = batch_size self.plot = plot self.extra_decay_time = extra_decay_time self.extra_std = extra_std self.best_frac = best_frac self.n_samples = n_samples self.init_std = init_std self.di...
':type algo: BatchPolopt'
def __init__(self, algo):
self.algo = algo
':param env: Environment :param policy: Policy :type policy: Policy :param baseline: Baseline :param scope: Scope for identifying the algorithm. Must be specified if running multiple algorithms simultaneously, each using different environments and policies :param n_itr: Number of iterations. :param start_itr: Starting ...
def __init__(self, env, policy, baseline, scope=None, n_itr=500, start_itr=0, batch_size=5000, max_path_length=500, discount=0.99, gae_lambda=1, plot=False, pause_for_plot=False, center_adv=True, positive_adv=False, store_paths=False, whole_paths=True, sampler_cls=None, sampler_args=None, **kwargs):
self.env = env self.policy = policy self.baseline = baseline self.scope = scope self.n_itr = n_itr self.current_itr = start_itr self.batch_size = batch_size self.max_path_length = max_path_length self.discount = discount self.gae_lambda = gae_lambda self.plot = plot self....
'Initialize the optimization procedure. If using theano / cgt, this may include declaring all the variables and compiling functions'
def init_opt(self):
raise NotImplementedError
'Returns all the data that should be saved in the snapshot for this iteration.'
def get_itr_snapshot(self, itr, samples_data):
raise NotImplementedError
':param env: Environment :param policy: Policy :param qf: Q function :param es: Exploration strategy :param batch_size: Number of samples for each minibatch. :param n_epochs: Number of epochs. Policy will be evaluated after each epoch. :param epoch_length: How many timesteps for each epoch. :param min_pool_size: Minimu...
def __init__(self, env, policy, qf, es, batch_size=32, n_epochs=200, epoch_length=1000, min_pool_size=10000, replay_pool_size=1000000, discount=0.99, max_path_length=250, qf_weight_decay=0.0, qf_update_method='adam', qf_learning_rate=0.001, policy_weight_decay=0, policy_update_method='adam', policy_learning_rate=0.001,...
self.env = env self.policy = policy self.qf = qf self.es = es self.batch_size = batch_size self.n_epochs = n_epochs self.epoch_length = epoch_length self.min_pool_size = min_pool_size self.replay_pool_size = replay_pool_size self.discount = discount self.max_path_length = max...
':param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood. ...
def __init__(self, input_shape, output_dim, mean_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=NL.rectify, optimizer=None, use_trust_region=True, step_size=0.01, learn_std=True, init_std=1.0, adaptive_std=False, std_share_network=False, std_hidden_sizes=(32, 32), std_nonlinearity=None, normalize_inputs=True,...
Serializable.quick_init(self, locals()) self._batchsize = batchsize self._subsample_factor = subsample_factor if (optimizer is None): if use_trust_region: optimizer = PenaltyLbfgsOptimizer() else: optimizer = LbfgsOptimizer() self._optimizer = optimizer if...
'Return the maximum likelihood estimate of the predicted y. :param xs: :return:'
def predict(self, xs):
return self._f_predict(xs)
'Sample one possible output from the prediction distribution. :param xs: :return:'
def sample_predict(self, xs):
(means, log_stds) = self._f_pdists(xs) return self._dist.sample(dict(mean=means, log_std=log_stds))
':param input_shape: usually for images of the form (width,height,channel) :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing ...
def __init__(self, name, input_shape, output_dim, hidden_sizes, conv_filters, conv_filter_sizes, conv_strides, conv_pads, hidden_nonlinearity=NL.rectify, mean_network=None, optimizer=None, use_trust_region=True, step_size=0.01, subsample_factor=1.0, batchsize=None, learn_std=True, init_std=1.0, adaptive_std=False, std_...
Serializable.quick_init(self, locals()) if (optimizer is None): if use_trust_region: optimizer = PenaltyLbfgsOptimizer('optimizer') else: optimizer = LbfgsOptimizer('optimizer') self._optimizer = optimizer self.input_shape = input_shape if (mean_network is Non...
'Return the maximum likelihood estimate of the predicted y. :param xs: :return:'
def predict(self, xs):
return self._f_predict(xs)
'Sample one possible output from the prediction distribution. :param xs: :return:'
def sample_predict(self, xs):
(means, log_stds) = self._f_pdists(xs) return self._dist.sample(dict(mean=means, log_std=log_stds))
':param input_shape: Shape of the input data. :param output_dim: Dimension of output. :param hidden_sizes: Number of hidden units of each layer of the mean network. :param hidden_nonlinearity: Non-linearity used for each layer of the mean network. :param optimizer: Optimizer for minimizing the negative log-likelihood. ...
def __init__(self, input_shape, output_dim, prob_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=NL.rectify, optimizer=None, use_trust_region=True, step_size=0.01, normalize_inputs=True, name=None):
Serializable.quick_init(self, locals()) if (optimizer is None): if use_trust_region: optimizer = PenaltyLbfgsOptimizer() else: optimizer = LbfgsOptimizer() self.output_dim = output_dim self._optimizer = optimizer if (prob_network is None): prob_network...
':param regressors: List of individual regressors'
def __init__(self, regressors):
Serializable.quick_init(self, locals()) self.regressors = regressors self.output_dims = [x.output_dim for x in regressors]
'Uniformly randomly sample a random elemnt of this space'
def sample(self, seed=0):
raise NotImplementedError
'Return boolean specifying if x is a valid member of this space'
def contains(self, x):
raise NotImplementedError
'The dimension of the flattened vector of the tensor representation'
@property def flat_dim(self):
raise NotImplementedError
'Create a Theano tensor variable given the name and extra dimensions prepended :param name: name of the variable :param extra_dims: extra dimensions in the front :return: the created tensor variable'
def new_tensor_variable(self, name, extra_dims):
raise NotImplementedError
'Two kinds of valid input: Box(-1.0, 1.0, (3,4)) # low and high are scalars, and shape is provided Box(np.array([-1.0,-2.0]), np.array([2.0,4.0])) # low and high are arrays of the same shape'
def __init__(self, low, high, shape=None):
if (shape is None): assert (low.shape == high.shape) self.low = low self.high = high else: assert (np.isscalar(low) and np.isscalar(high)) self.low = (low + np.zeros(shape)) self.high = (high + np.zeros(shape))
':type algo: BatchPolopt :param n_backtrack: Number of past policies to update from :param n_is_pretrain: Number of importance sampling iterations to perform in beginning of training :param init_is: (True/False) set initial iteration (after pretrain) an importance sampling iteration :param skip_is_itrs: (True/False) do...
def __init__(self, algo, n_backtrack='all', n_is_pretrain=0, init_is=0, skip_is_itrs=False, hist_variance_penalty=0.0, max_is_ratio=0, ess_threshold=0):
self.n_backtrack = n_backtrack self.n_is_pretrain = n_is_pretrain self.skip_is_itrs = skip_is_itrs self.hist_variance_penalty = hist_variance_penalty self.max_is_ratio = max_is_ratio self.ess_threshold = ess_threshold self._hist = [] self._is_itr = init_is super(ISSampler, self).__in...
'History of policies that have interacted with the environment and the data from interaction episode(s)'
@property def history(self):
return self._hist
'Store policy distribution and paths in history'
def add_history(self, policy_distribution, paths):
self._hist.append((policy_distribution, paths))
'Get list of (distribution, data) tuples from history'
def get_history_list(self, n_past='all'):
if (n_past == 'all'): return self._hist return self._hist[(- min(n_past, len(self._hist))):]
'Return image json metadata, checksum and its blob.'
def fetch_image(self, image_id):
resp = requests.get('{0}/v1/images/{1}/json'.format(self.registry_endpoint, image_id)) self.assertEqual(resp.status_code, 200, resp.text) resp = requests.get('{0}/v1/images/{1}/json'.format(self.registry_endpoint, image_id), headers={'Authorization': ('Token ' + self.token)}) self.assertEqual(resp.st...
'Used for debugging only.'
def _debug_key(self, key):
orig_meth = key.bucket.connection.make_request def new_meth(*args, **kwargs): print ('#' * 16) print args print kwargs print ('#' * 16) return orig_meth(*args, **kwargs) key.bucket.connection.make_request = new_meth
'Get a URL for content at path Get a URL to which client can be redirected to get the content from the path. Return None if not supported by this engine. Note, this feature will only be used if the `storage_redirect` configuration key is set to `True`.'
def content_redirect_url(self, path):
return None
'Method to get content.'
def get_content(self, path):
raise NotImplementedError(('You must implement get_content(self, path) on your storage %s' % self.__class__.__name__))
'Method to put content.'
def put_content(self, path, content):
raise NotImplementedError(('You must implement put_content(self, path, content) on %s' % self.__class__.__name__))
'Method to stream read.'
def stream_read(self, path, bytes_range=None):
raise NotImplementedError(('You must implement stream_read(self, path, , bytes_range=None) ' + ('on your storage %s' % self.__class__.__name__)))
'Method to stream write.'
def stream_write(self, path, fp):
raise NotImplementedError(('You must implement stream_write(self, path, fp) ' + ('on your storage %s' % self.__class__.__name__)))
'Method to list directory.'
def list_directory(self, path=None):
raise NotImplementedError(('You must implement list_directory(self, path=None) ' + ('on your storage %s' % self.__class__.__name__)))
'Method to test exists.'
def exists(self, path):
raise NotImplementedError(('You must implement exists(self, path) on your storage %s' % self.__class__.__name__))
'Method to remove.'
def remove(self, path):
raise NotImplementedError(('You must implement remove(self, path) on your storage %s' % self.__class__.__name__))
'Method to get the size.'
def get_size(self, path):
raise NotImplementedError(('You must implement get_size(self, path) on your storage %s' % self.__class__.__name__))
'Iterate through repositories in storage This helper is useful for building an initial database for your search index. Yields dictionaries: {\'name\': name, \'description\': description}'
def _walk_storage(self, store):
try: namespace_paths = list(store.list_directory(path=store.repositories)) except exceptions.FileNotFoundError: namespace_paths = [] for namespace_path in namespace_paths: namespace = namespace_path.rsplit('/', 1)[(-1)] try: repository_paths = list(store.list_dire...
'Return a list of results matching search_term The list elements should be dictionaries: {\'name\': name, \'description\': description}'
def results(self, search_term=None):
raise NotImplementedError('results method for {0!r}'.format(self))
'Return the length of the queue.'
def __len__(self):
return self.redis.llen(self.key)
'Get a slice or a particular index.'
def __getitem__(self, val):
try: slice = self.redis.lrange(self.key, val.start, (val.stop - 1)) return [self._unpack(i) for i in slice] except AttributeError: return self._unpack(self.redis.lindex(self.key, val)) except Exception as e: log.error(('Get item failed ** %s' % repr(e))) r...
'Prepares a message to go into Redis.'
def _pack(self, val):
return self.serializer.dumps(val, 1)
'Unpacks a message stored in Redis.'
def _unpack(self, val):
try: return self.serializer.loads(val) except TypeError: return None
'Destructively dump the contents of the queue into fp.'
def dump(self, fobj):
next = self.redis.rpop(self.key) while next: fobj.write(next) next = self.redis.rpop(self.key)
'Load the contents of the provided fobj into the queue.'
def load(self, fobj):
try: while True: val = self._pack(self.serializer.load(fobj)) self.redis.lpush(self.key, val) except Exception: return
'Destructively dump the contents of the queue into fname.'
def dumpfname(self, fname, truncate=False):
if truncate: with file(fname, 'w+') as f: self.dump(f) else: with file(fname, 'a+') as f: self.dump(f)
'Load the contents of the contents of fname into the queue.'
def loadfname(self, fname):
with file(fname) as f: self.load(f)
'Extends the elements in the queue.'
def extend(self, vals):
with self.redis.pipeline(transaction=False) as pipe: for val in vals: pipe.lpush(self.key, self._pack(val)) pipe.execute()
'Look at the next item in the queue.'
def peek(self):
return self[(-1)]
'Return all elements as a Python list.'
def elements(self):
return [self._unpack(o) for o in self.redis.lrange(self.key, 0, (-1))]
'Return all elements as JSON object.'
def elements_as_json(self):
return json.dumps(self.elements)
'Removes all the elements in the queue.'
def clear(self):
self.redis.delete(self.key)
'Extends the elements in the queue.'
def extend(self, vals):
with self.redis.pipeline() as pipe: for val in vals: pipe.lpush(self.key, self._pack(val)) pipe.ltrim(self.key, 0, (self.size - 1)) pipe.execute()
'The name of the volume.'
@property def name(self):
return self.attrs['Name']
'Remove this volume. Args: force (bool): Force removal of volumes that were already removed out of band by the volume driver plugin. Raises: :py:class:`docker.errors.APIError` If volume failed to remove.'
def remove(self, force=False):
return self.client.api.remove_volume(self.id, force=force)
'Create a volume. Args: name (str): Name of the volume. If not specified, the engine generates a name. driver (str): Name of the driver used to create the volume driver_opts (dict): Driver options as a key-value dictionary labels (dict): Labels to set on the volume Returns: (:py:class:`Volume`): The volume created. Ra...
def create(self, name=None, **kwargs):
obj = self.client.api.create_volume(name, **kwargs) return self.prepare_model(obj)
'Get a volume. Args: volume_id (str): Volume name. Returns: (:py:class:`Volume`): The volume. Raises: :py:class:`docker.errors.NotFound` If the volume does not exist. :py:class:`docker.errors.APIError` If the server returns an error.'
def get(self, volume_id):
return self.prepare_model(self.client.api.inspect_volume(volume_id))
'List volumes. Similar to the ``docker volume ls`` command. Args: filters (dict): Server-side list filtering options. Returns: (list of :py:class:`Volume`): The volumes. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def list(self, **kwargs):
resp = self.client.api.volumes(**kwargs) if (not resp.get('Volumes')): return [] return [self.prepare_model(obj) for obj in resp['Volumes']]
'The plugin\'s name.'
@property def name(self):
return self.attrs.get('Name')
'Whether the plugin is enabled.'
@property def enabled(self):
return self.attrs.get('Enabled')
'A dictionary representing the plugin\'s configuration.'
@property def settings(self):
return self.attrs.get('Settings')
'Update the plugin\'s settings. Args: options (dict): A key-value mapping of options. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def configure(self, options):
self.client.api.configure_plugin(self.name, options) self.reload()
'Disable the plugin. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def disable(self):
self.client.api.disable_plugin(self.name) self.reload()
'Enable the plugin. Args: timeout (int): Timeout in seconds. Default: 0 Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def enable(self, timeout=0):
self.client.api.enable_plugin(self.name, timeout) self.reload()
'Push the plugin to a remote registry. Returns: A dict iterator streaming the status of the upload. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def push(self):
return self.client.api.push_plugin(self.name)
'Remove the plugin from the server. Args: force (bool): Remove even if the plugin is enabled. Default: False Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def remove(self, force=False):
return self.client.api.remove_plugin(self.name, force=force)
'Upgrade the plugin. Args: remote (string): Remote reference to upgrade to. The ``:latest`` tag is optional and is the default if omitted. Default: this plugin\'s name. Returns: A generator streaming the decoded API logs'
def upgrade(self, remote=None):
if self.enabled: raise errors.DockerError('Plugin must be disabled before upgrading.') if (remote is None): remote = self.name privileges = self.client.api.plugin_privileges(remote) for d in self.client.api.upgrade_plugin(self.name, remote, privileges): (yield d) ...
'Create a new plugin. Args: name (string): The name of the plugin. The ``:latest`` tag is optional, and is the default if omitted. plugin_data_dir (string): Path to the plugin data directory. Plugin data directory must contain the ``config.json`` manifest file and the ``rootfs`` directory. gzip (bool): Compress the con...
def create(self, name, plugin_data_dir, gzip=False):
self.client.api.create_plugin(name, plugin_data_dir, gzip) return self.get(name)
'Gets a plugin. Args: name (str): The name of the plugin. Returns: (:py:class:`Plugin`): The plugin. Raises: :py:class:`docker.errors.NotFound` If the plugin does not exist. :py:class:`docker.errors.APIError` If the server returns an error.'
def get(self, name):
return self.prepare_model(self.client.api.inspect_plugin(name))
'Pull and install a plugin. Args: remote_name (string): Remote reference for the plugin to install. The ``:latest`` tag is optional, and is the default if omitted. local_name (string): Local name for the pulled plugin. The ``:latest`` tag is optional, and is the default if omitted. Optional. Returns: (:py:class:`Plugin...
def install(self, remote_name, local_name=None):
privileges = self.client.api.plugin_privileges(remote_name) it = self.client.api.pull_plugin(remote_name, privileges, local_name) for data in it: pass return self.get((local_name or remote_name))
'List plugins installed on the server. Returns: (list of :py:class:`Plugin`): The plugins. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def list(self):
resp = self.client.api.plugins() return [self.prepare_model(r) for r in resp]
'The version number of the service. If this is not the same as the server, the :py:meth:`update` function will not work and you will need to call :py:meth:`reload` before calling it again.'
@property def version(self):
return self.attrs.get('Version').get('Index')
'Update the node\'s configuration. Args: node_spec (dict): Configuration settings to update. Any values not provided will be removed. Default: ``None`` Returns: `True` if the request went through. Raises: :py:class:`docker.errors.APIError` If the server returns an error. Example: >>> node_spec = {\'Availability\': \'ac...
def update(self, node_spec):
return self.client.api.update_node(self.id, self.version, node_spec)
'Remove this node from the swarm. Args: force (bool): Force remove an active node. Default: `False` Returns: `True` if the request was successful. Raises: :py:class:`docker.errors.NotFound` If the node doesn\'t exist in the swarm. :py:class:`docker.errors.APIError` If the server returns an error.'
def remove(self, force=False):
return self.client.api.remove_node(self.id, force=force)
'Get a node. Args: node_id (string): ID of the node to be inspected. Returns: A :py:class:`Node` object. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def get(self, node_id):
return self.prepare_model(self.client.api.inspect_node(node_id))
'List swarm nodes. Args: filters (dict): Filters to process on the nodes list. Valid filters: ``id``, ``name``, ``membership`` and ``role``. Default: ``None`` Returns: A list of :py:class:`Node` objects. Raises: :py:class:`docker.errors.APIError` If the server returns an error. Example: >>> client.nodes.list(filters={\...
def list(self, *args, **kwargs):
return [self.prepare_model(n) for n in self.client.api.nodes(*args, **kwargs)]
'The name of the network.'
@property def name(self):
return self.attrs.get('Name')
'The containers that are connected to the network, as a list of :py:class:`~docker.models.containers.Container` objects.'
@property def containers(self):
return [self.client.containers.get(cid) for cid in (self.attrs.get('Containers') or {}).keys()]
'Connect a container to this network. Args: container (str): Container to connect to this network, as either an ID, name, or :py:class:`~docker.models.containers.Container` object. aliases (:py:class:`list`): A list of aliases for this endpoint. Names in that list can be used within the network to reach the container. ...
def connect(self, container, *args, **kwargs):
if isinstance(container, Container): container = container.id return self.client.api.connect_container_to_network(container, self.id, *args, **kwargs)
'Disconnect a container from this network. Args: container (str): Container to disconnect from this network, as either an ID, name, or :py:class:`~docker.models.containers.Container` object. force (bool): Force the container to disconnect from a network. Default: ``False`` Raises: :py:class:`docker.errors.APIError` If ...
def disconnect(self, container, *args, **kwargs):
if isinstance(container, Container): container = container.id return self.client.api.disconnect_container_from_network(container, self.id, *args, **kwargs)
'Remove this network. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def remove(self):
return self.client.api.remove_network(self.id)
'Create a network. Similar to the ``docker network create``. Args: name (str): Name of the network driver (str): Name of the driver used to create the network options (dict): Driver options as a key-value dictionary ipam (dict): Optional custom IP scheme for the network. Created with :py:class:`~docker.types.IPAMConfig...
def create(self, name, *args, **kwargs):
resp = self.client.api.create_network(name, *args, **kwargs) return self.get(resp['Id'])
'Get a network by its ID. Args: network_id (str): The ID of the network. Returns: (:py:class:`Network`) The network. Raises: :py:class:`docker.errors.NotFound` If the network does not exist. :py:class:`docker.errors.APIError` If the server returns an error.'
def get(self, network_id):
return self.prepare_model(self.client.api.inspect_network(network_id))
'List networks. Similar to the ``docker networks ls`` command. Args: names (:py:class:`list`): List of names to filter by. ids (:py:class:`list`): List of ids to filter by. Returns: (list of :py:class:`Network`) The networks on the server. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def list(self, *args, **kwargs):
resp = self.client.api.networks(*args, **kwargs) return [self.prepare_model(item) for item in resp]
'The name of the container.'
@property def name(self):
if (self.attrs.get('Name') is not None): return self.attrs['Name'].lstrip('/')
'The image of the container.'
@property def image(self):
image_id = self.attrs['Image'] if (image_id is None): return None return self.client.images.get(image_id.split(':')[1])
'The labels of a container as dictionary.'
@property def labels(self):
result = self.attrs['Config'].get('Labels') return (result or {})
'The status of the container. For example, ``running``, or ``exited``.'
@property def status(self):
return self.attrs['State']['Status']
'Attach to this container. :py:meth:`logs` is a wrapper around this method, which you can use instead if you want to fetch/stream container output without first retrieving the entire backlog. Args: stdout (bool): Include stdout. stderr (bool): Include stderr. stream (bool): Return container output progressively as an i...
def attach(self, **kwargs):
return self.client.api.attach(self.id, **kwargs)
'Like :py:meth:`attach`, but returns the underlying socket-like object for the HTTP request. Args: params (dict): Dictionary of request parameters (e.g. ``stdout``, ``stderr``, ``stream``). ws (bool): Use websockets instead of raw HTTP. Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def attach_socket(self, **kwargs):
return self.client.api.attach_socket(self.id, **kwargs)
'Commit a container to an image. Similar to the ``docker commit`` command. Args: repository (str): The repository to push the image to tag (str): The tag to push message (str): A commit message author (str): The name of the author changes (str): Dockerfile instructions to apply while committing conf (dict): The configu...
def commit(self, repository=None, tag=None, **kwargs):
resp = self.client.api.commit(self.id, repository=repository, tag=tag, **kwargs) return self.client.images.get(resp['Id'])
'Inspect changes on a container\'s filesystem. Returns: (str) Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def diff(self):
return self.client.api.diff(self.id)
'Run a command inside this container. Similar to ``docker exec``. Args: cmd (str or list): Command to be executed stdout (bool): Attach to stdout. Default: ``True`` stderr (bool): Attach to stderr. Default: ``True`` stdin (bool): Attach to stdin. Default: ``False`` tty (bool): Allocate a pseudo-TTY. Default: False priv...
def exec_run(self, cmd, stdout=True, stderr=True, stdin=False, tty=False, privileged=False, user='', detach=False, stream=False, socket=False, environment=None):
resp = self.client.api.exec_create(self.id, cmd, stdout=stdout, stderr=stderr, stdin=stdin, tty=tty, privileged=privileged, user=user, environment=environment) return self.client.api.exec_start(resp['Id'], detach=detach, tty=tty, stream=stream, socket=socket)
'Export the contents of the container\'s filesystem as a tar archive. Returns: (str): The filesystem tar archive Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def export(self):
return self.client.api.export(self.id)
'Retrieve a file or folder from the container in the form of a tar archive. Args: path (str): Path to the file or folder to retrieve Returns: (tuple): First element is a raw tar data stream. Second element is a dict containing ``stat`` information on the specified ``path``. Raises: :py:class:`docker.errors.APIError` If...
def get_archive(self, path):
return self.client.api.get_archive(self.id, path)
'Kill or send a signal to the container. Args: signal (str or int): The signal to send. Defaults to ``SIGKILL`` Raises: :py:class:`docker.errors.APIError` If the server returns an error.'
def kill(self, signal=None):
return self.client.api.kill(self.id, signal=signal)
'Get logs from this container. Similar to the ``docker logs`` command. The ``stream`` parameter makes the ``logs`` function return a blocking generator you can iterate over to retrieve log output as it happens. Args: stdout (bool): Get ``STDOUT`` stderr (bool): Get ``STDERR`` stream (bool): Stream the response timestam...
def logs(self, **kwargs):
return self.client.api.logs(self.id, **kwargs)