sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def receive_data(socket): """Receive an answer from the daemon and return the response. Args: socket (socket.socket): A socket that is connected to the daemon. Returns: dir or string: The unpickled answer. """ answer = b"" while True: packet = socket.recv(4096) if not packet: break answer += packet response = pickle.loads(answer) socket.close() return response
Receive an answer from the daemon and return the response. Args: socket (socket.socket): A socket that is connected to the daemon. Returns: dir or string: The unpickled answer.
entailment
def connect_socket(root_dir): """Connect to a daemon's socket. Args: root_dir (str): The directory that used as root by the daemon. Returns: socket.socket: A socket that is connected to the daemon. """ # Get config directory where the daemon socket is located config_dir = os.path.join(root_dir, '.config/pueue') # Create Socket and exit with 1, if socket can't be created try: client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) socket_path = os.path.join(config_dir, 'pueue.sock') if os.path.exists(socket_path): client.connect(socket_path) else: print("Socket doesn't exist") raise Exception except: print("Error connecting to socket. Make sure the daemon is running") sys.exit(1) return client
Connect to a daemon's socket. Args: root_dir (str): The directory that used as root by the daemon. Returns: socket.socket: A socket that is connected to the daemon.
entailment
def from_raw(conn, raw): '''Return a new response from a raw buffer''' frame_type = struct.unpack('>l', raw[0:4])[0] message = raw[4:] if frame_type == FRAME_TYPE_MESSAGE: return Message(conn, frame_type, message) elif frame_type == FRAME_TYPE_RESPONSE: return Response(conn, frame_type, message) elif frame_type == FRAME_TYPE_ERROR: return Error(conn, frame_type, message) else: raise TypeError('Unknown frame type: %s' % frame_type)
Return a new response from a raw buffer
entailment
def pack(cls, data): '''Pack the provided data into a Response''' return struct.pack('>ll', len(data) + 4, cls.FRAME_TYPE) + data
Pack the provided data into a Response
entailment
def fin(self): '''Indicate that this message is finished processing''' self.connection.fin(self.id) self.processed = True
Indicate that this message is finished processing
entailment
def req(self, timeout): '''Re-queue a message''' self.connection.req(self.id, timeout) self.processed = True
Re-queue a message
entailment
def handle(self): '''Make sure this message gets either 'fin' or 'req'd''' try: yield self except: # Requeue the message and raise the original exception typ, value, trace = sys.exc_info() if not self.processed: try: self.req(self.delay()) except socket.error: self.connection.close() raise typ, value, trace else: if not self.processed: try: self.fin() except socket.error: self.connection.close()
Make sure this message gets either 'fin' or 'req'd
entailment
def find(cls, name): '''Find the exception class by name''' if not cls.mapping: # pragma: no branch for _, obj in inspect.getmembers(exceptions): if inspect.isclass(obj): if issubclass(obj, exceptions.NSQException): # pragma: no branch if hasattr(obj, 'name'): cls.mapping[obj.name] = obj klass = cls.mapping.get(name) if klass == None: raise TypeError('No matching exception for %s' % name) return klass
Find the exception class by name
entailment
def exception(self): '''Return an instance of the corresponding exception''' code, _, message = self.data.partition(' ') return self.find(code)(message)
Return an instance of the corresponding exception
entailment
def parse_gdb_version(line): r"""Parse the gdb version from the gdb header. From GNU coding standards: the version starts after the last space of the first line. >>> DOCTEST_GDB_VERSIONS = [ ... r'~"GNU gdb (GDB) 7.5.1\n"', ... r'~"GNU gdb (Sourcery CodeBench Lite 2011.09-69) 7.2.50.20100908-cvs\n"', ... r'~"GNU gdb (GDB) SUSE (7.5.1-2.5.1)\n"', ... r'~"GNU gdb (GDB) Fedora (7.6-32.fc19)\n"', ... r'~"GNU gdb (GDB) 7.6.1.dummy\n"', ... ] >>> for header in DOCTEST_GDB_VERSIONS: ... print(parse_gdb_version(header)) 7.5.1 7.2.50.20100908 7.5.1 7.6 7.6.1 """ if line.startswith('~"') and line.endswith(r'\n"'): version = line[2:-3].rsplit(' ', 1) if len(version) == 2: # Strip after first non digit or '.' character. Allow for linux # Suse non conformant implementation that encloses the version in # brackets. version = ''.join(takewhile(lambda x: x.isdigit() or x == '.', version[1].lstrip('('))) return version.strip('.') return ''
r"""Parse the gdb version from the gdb header. From GNU coding standards: the version starts after the last space of the first line. >>> DOCTEST_GDB_VERSIONS = [ ... r'~"GNU gdb (GDB) 7.5.1\n"', ... r'~"GNU gdb (Sourcery CodeBench Lite 2011.09-69) 7.2.50.20100908-cvs\n"', ... r'~"GNU gdb (GDB) SUSE (7.5.1-2.5.1)\n"', ... r'~"GNU gdb (GDB) Fedora (7.6-32.fc19)\n"', ... r'~"GNU gdb (GDB) 7.6.1.dummy\n"', ... ] >>> for header in DOCTEST_GDB_VERSIONS: ... print(parse_gdb_version(header)) 7.5.1 7.2.50.20100908 7.5.1 7.6 7.6.1
entailment
def spawn_gdb(pid, address=DFLT_ADDRESS, gdb='gdb', verbose=False, ctx=None, proc_iut=None): """Spawn gdb and attach to a process.""" parent, child = socket.socketpair() proc = Popen([gdb, '--interpreter=mi', '-nx'], bufsize=0, stdin=child, stdout=child, stderr=STDOUT) child.close() connections = {} gdb = GdbSocket(ctx, address, proc, proc_iut, parent, verbose, connections) gdb.mi_command('-target-attach %d' % pid) gdb.cli_command('python import pdb_clone.bootstrappdb_gdb') asyncore.loop(map=connections) proc.wait() return gdb.error
Spawn gdb and attach to a process.
entailment
def attach_loop(argv): """Spawn the process, then repeatedly attach to the process.""" # Check if the pdbhandler module is built into python. p = Popen((sys.executable, '-X', 'pdbhandler', '-c', 'import pdbhandler; pdbhandler.get_handler().host'), stdout=PIPE, stderr=STDOUT) p.wait() use_xoption = True if p.returncode == 0 else False # Spawn the process. args = [sys.executable] if use_xoption: # Use SIGUSR2 as faulthandler is set on python test suite with # SIGUSR1. args.extend(['-X', 'pdbhandler=localhost 7935 %d' % signal.SIGUSR2]) args.extend(argv) proc = Popen(args) else: args.extend(argv) proc = Popen(args) # Repeatedly attach to the process using the '-X' python option or gdb. ctx = Context() error = None time.sleep(.5 + random.random()) while not error and proc.poll() is None: if use_xoption: os.kill(proc.pid, signal.SIGUSR2) connections = {} dev_null = io.StringIO() if PY3 else StringIO.StringIO() asock = AttachSocketWithDetach(connections, stdout=dev_null) asock.create_socket(socket.AF_INET, socket.SOCK_STREAM) connect_process(asock, ctx, proc) asyncore.loop(map=connections) else: error = spawn_gdb(proc.pid, ctx=ctx, proc_iut=proc) time.sleep(random.random()) if error and gdb_terminated(error): error = None if proc.poll() is None: proc.terminate() else: print('pdb-attach: program under test return code:', proc.wait()) result = str(ctx.result) if result: print(result) return error
Spawn the process, then repeatedly attach to the process.
entailment
def skip(self): """Skip this py-pdb command to avoid attaching within the same loop.""" line = self.line self.line = '' # 'line' is the statement line of the previous py-pdb command. if line in self.lines: if not self.skipping: self.skipping = True printflush('Skipping lines', end='') printflush('.', end='') return True elif line: self.lines.append(line) if len(self.lines) > 30: self.lines.popleft() return False
Skip this py-pdb command to avoid attaching within the same loop.
entailment
def rotate(self, log): """Move the current log to a new file with timestamp and create a new empty log file.""" self.write(log, rotate=True) self.write({})
Move the current log to a new file with timestamp and create a new empty log file.
entailment
def write(self, log, rotate=False): """Write the output of all finished processes to a compiled log file.""" # Get path for logfile if rotate: timestamp = time.strftime('-%Y%m%d-%H%M') logPath = os.path.join(self.log_dir, 'queue{}.log'.format(timestamp)) else: logPath = os.path.join(self.log_dir, 'queue.log') # Remove existing Log if os.path.exists(logPath): os.remove(logPath) log_file = open(logPath, 'w') log_file.write('Pueue log for executed Commands: \n \n') # Format, color and write log for key, logentry in log.items(): if logentry.get('returncode') is not None: try: # Get returncode color: returncode = logentry['returncode'] if returncode == 0: returncode = Color('{autogreen}' + '{}'.format(returncode) + '{/autogreen}') else: returncode = Color('{autored}' + '{}'.format(returncode) + '{/autored}') # Write command id with returncode and actual command log_file.write( Color('{autoyellow}' + 'Command #{} '.format(key) + '{/autoyellow}') + 'exited with returncode {}: \n'.format(returncode) + '"{}" \n'.format(logentry['command']) ) # Write path log_file.write('Path: {} \n'.format(logentry['path'])) # Write times log_file.write('Start: {}, End: {} \n' .format(logentry['start'], logentry['end'])) # Write STDERR if logentry['stderr']: log_file.write(Color('{autored}Stderr output: {/autored}\n ') + logentry['stderr']) # Write STDOUT if len(logentry['stdout']) > 0: log_file.write(Color('{autogreen}Stdout output: {/autogreen}\n ') + logentry['stdout']) log_file.write('\n') except Exception as a: print('Failed while writing to log file. Wrong file permissions?') print('Exception: {}'.format(str(a))) log_file.close()
Write the output of all finished processes to a compiled log file.
entailment
def remove_old(self, max_log_time): """Remove all logs which are older than the specified time.""" files = glob.glob('{}/queue-*'.format(self.log_dir)) files = list(map(lambda x: os.path.basename(x), files)) for log_file in files: # Get time stamp from filename name = os.path.splitext(log_file)[0] timestamp = name.split('-', maxsplit=1)[1] # Get datetime from time stamp time = datetime.strptime(timestamp, '%Y%m%d-%H%M') now = datetime.now() # Get total delta in seconds delta = now - time seconds = delta.total_seconds() # Delete log file, if the delta is bigger than the specified log time if seconds > int(max_log_time): log_filePath = os.path.join(self.log_dir, log_file) os.remove(log_filePath)
Remove all logs which are older than the specified time.
entailment
def wrap(function, *args, **kwargs): '''Wrap a function that returns a request with some exception handling''' try: req = function(*args, **kwargs) logger.debug('Got %s: %s', req.status_code, req.content) if req.status_code == 200: return req else: raise ClientException(req.reason, req.content) except ClientException: raise except Exception as exc: raise ClientException(exc)
Wrap a function that returns a request with some exception handling
entailment
def json_wrap(function, *args, **kwargs): '''Return the json content of a function that returns a request''' try: # Some responses have data = None, but they generally signal a # successful API call as well. response = json.loads(function(*args, **kwargs).content) if 'data' in response: return response['data'] or True else: return response except Exception as exc: raise ClientException(exc)
Return the json content of a function that returns a request
entailment
def ok_check(function, *args, **kwargs): '''Ensure that the response body is OK''' req = function(*args, **kwargs) if req.content.lower() != 'ok': raise ClientException(req.content) return req.content
Ensure that the response body is OK
entailment
def get(self, path, *args, **kwargs): '''GET the provided endpoint''' target = self._host.relative(path).utf8 if not isinstance(target, basestring): # on older versions of the `url` library, .utf8 is a method, not a property target = target() params = kwargs.get('params', {}) params.update(self._params) kwargs['params'] = params logger.debug('GET %s with %s, %s', target, args, kwargs) return requests.get(target, *args, **kwargs)
GET the provided endpoint
entailment
def decode_resumable_upload_bitmap(bitmap_node, number_of_units): """Decodes bitmap_node to hash of unit_id: is_uploaded bitmap_node -- bitmap node of resumable_upload with 'count' number and 'words' containing array number_of_units -- number of units we are uploading to define the number of bits for bitmap """ bitmap = 0 for token_id in range(int(bitmap_node['count'])): value = int(bitmap_node['words'][token_id]) bitmap = bitmap | (value << (0xf * token_id)) result = {} for unit_id in range(number_of_units): mask = 1 << unit_id result[unit_id] = (bitmap & mask) == mask return result
Decodes bitmap_node to hash of unit_id: is_uploaded bitmap_node -- bitmap node of resumable_upload with 'count' number and 'words' containing array number_of_units -- number of units we are uploading to define the number of bits for bitmap
entailment
def compute_hash_info(fd, unit_size=None): """Get MediaFireHashInfo structure from the fd, unit_size fd -- file descriptor - expects exclusive access because of seeking unit_size -- size of a single unit Returns MediaFireHashInfo: hi.file -- sha256 of the whole file hi.units -- list of sha256 hashes for each unit """ logger.debug("compute_hash_info(%s, unit_size=%s)", fd, unit_size) fd.seek(0, os.SEEK_END) file_size = fd.tell() fd.seek(0, os.SEEK_SET) units = [] unit_counter = 0 file_hash = hashlib.sha256() unit_hash = hashlib.sha256() for chunk in iter(lambda: fd.read(HASH_CHUNK_SIZE_BYTES), b''): file_hash.update(chunk) unit_hash.update(chunk) unit_counter += len(chunk) if unit_size is not None and unit_counter == unit_size: # flush the current unit hash units.append(unit_hash.hexdigest().lower()) unit_counter = 0 unit_hash = hashlib.sha256() if unit_size is not None and unit_counter > 0: # leftover block units.append(unit_hash.hexdigest().lower()) fd.seek(0, os.SEEK_SET) return MediaFireHashInfo( file=file_hash.hexdigest().lower(), units=units, size=file_size )
Get MediaFireHashInfo structure from the fd, unit_size fd -- file descriptor - expects exclusive access because of seeking unit_size -- size of a single unit Returns MediaFireHashInfo: hi.file -- sha256 of the whole file hi.units -- list of sha256 hashes for each unit
entailment
def upload(self, fd, name=None, folder_key=None, filedrop_key=None, path=None, action_on_duplicate=None): """Upload file, returns UploadResult object fd -- file-like object to upload from, expects exclusive access name -- file name folder_key -- folderkey of the target folder path -- path to file relative to folder_key filedrop_key -- filedrop to use instead of folder_key action_on_duplicate -- skip, keep, replace """ # Get file handle content length in the most reliable way fd.seek(0, os.SEEK_END) size = fd.tell() fd.seek(0, os.SEEK_SET) if size > UPLOAD_SIMPLE_LIMIT_BYTES: resumable = True else: resumable = False logger.debug("Calculating checksum") hash_info = compute_hash_info(fd) if hash_info.size != size: # Has the file changed beween computing the hash # and calling upload()? raise ValueError("hash_info.size mismatch") upload_info = _UploadInfo(fd=fd, name=name, folder_key=folder_key, hash_info=hash_info, size=size, path=path, filedrop_key=filedrop_key, action_on_duplicate=action_on_duplicate) # Check whether file is present check_result = self._upload_check(upload_info, resumable) upload_result = None upload_func = None folder_key = check_result.get('folder_key', None) if folder_key is not None: # We know precisely what folder_key to use, drop path upload_info.folder_key = folder_key upload_info.path = None if check_result['hash_exists'] == 'yes': # file exists somewhere in MediaFire if check_result['in_folder'] == 'yes' and \ check_result['file_exists'] == 'yes': # file exists in this directory different_hash = check_result.get('different_hash', 'no') if different_hash == 'no': # file is already there upload_func = self._upload_none if not upload_func: # different hash or in other folder upload_func = self._upload_instant if not upload_func: if resumable: resumable_upload_info = check_result['resumable_upload'] upload_info.hash_info = compute_hash_info( fd, int(resumable_upload_info['unit_size'])) upload_func = self._upload_resumable else: upload_func = self._upload_simple # Retry retriable exceptions retries = UPLOAD_RETRY_COUNT while retries > 0: try: # Provide check_result to avoid calling API twice upload_result = upload_func(upload_info, check_result) except (RetriableUploadError, MediaFireConnectionError): retries -= 1 logger.exception("%s failed (%d retries left)", upload_func.__name__, retries) # Refresh check_result for next iteration check_result = self._upload_check(upload_info, resumable) except Exception: logger.exception("%s failed", upload_func) break else: break if upload_result is None: raise UploadError("Upload failed") return upload_result
Upload file, returns UploadResult object fd -- file-like object to upload from, expects exclusive access name -- file name folder_key -- folderkey of the target folder path -- path to file relative to folder_key filedrop_key -- filedrop to use instead of folder_key action_on_duplicate -- skip, keep, replace
entailment
def _poll_upload(self, upload_key, action): """Poll upload until quickkey is found upload_key -- upload_key returned by upload/* functions """ if len(upload_key) != UPLOAD_KEY_LENGTH: # not a regular 11-char-long upload key # There is no API to poll filedrop uploads return UploadResult( action=action, quickkey=None, hash_=None, filename=None, size=None, created=None, revision=None ) quick_key = None while quick_key is None: poll_result = self._api.upload_poll(upload_key) doupload = poll_result['doupload'] logger.debug("poll(%s): status=%d, description=%s, filename=%s," " result=%d", upload_key, int(doupload['status']), doupload['description'], doupload['filename'], int(doupload['result'])) if int(doupload['result']) != 0: break if doupload['fileerror'] != '': # TODO: we may have to handle this a bit more dramatically logger.warning("poll(%s): fileerror=%d", upload_key, int(doupload['fileerror'])) break if int(doupload['status']) == STATUS_NO_MORE_REQUESTS: quick_key = doupload['quickkey'] elif int(doupload['status']) == STATUS_UPLOAD_IN_PROGRESS: # BUG: http://forum.mediafiredev.com/showthread.php?588 raise RetriableUploadError( "Invalid state transition ({})".format( doupload['description'] ) ) else: time.sleep(UPLOAD_POLL_INTERVAL) return UploadResult( action=action, quickkey=doupload['quickkey'], hash_=doupload['hash'], filename=doupload['filename'], size=doupload['size'], created=doupload['created'], revision=doupload['revision'] )
Poll upload until quickkey is found upload_key -- upload_key returned by upload/* functions
entailment
def _upload_check(self, upload_info, resumable=False): """Wrapper around upload/check""" return self._api.upload_check( filename=upload_info.name, size=upload_info.size, hash_=upload_info.hash_info.file, folder_key=upload_info.folder_key, filedrop_key=upload_info.filedrop_key, path=upload_info.path, resumable=resumable )
Wrapper around upload/check
entailment
def _upload_none(self, upload_info, check_result): """Dummy upload function for when we don't actually upload""" return UploadResult( action=None, quickkey=check_result['duplicate_quickkey'], hash_=upload_info.hash_info.file, filename=upload_info.name, size=upload_info.size, created=None, revision=None )
Dummy upload function for when we don't actually upload
entailment
def _upload_instant(self, upload_info, _=None): """Instant upload and return quickkey Can be used when the file is already stored somewhere in MediaFire upload_info -- UploadInfo object check_result -- ignored """ result = self._api.upload_instant( upload_info.name, upload_info.size, upload_info.hash_info.file, path=upload_info.path, folder_key=upload_info.folder_key, filedrop_key=upload_info.filedrop_key, action_on_duplicate=upload_info.action_on_duplicate ) return UploadResult( action='upload/instant', quickkey=result['quickkey'], filename=result['filename'], revision=result['new_device_revision'], hash_=upload_info.hash_info.file, size=upload_info.size, created=None )
Instant upload and return quickkey Can be used when the file is already stored somewhere in MediaFire upload_info -- UploadInfo object check_result -- ignored
entailment
def _upload_simple(self, upload_info, _=None): """Simple upload and return quickkey Can be used for small files smaller than UPLOAD_SIMPLE_LIMIT_BYTES upload_info -- UploadInfo object check_result -- ignored """ upload_result = self._api.upload_simple( upload_info.fd, upload_info.name, folder_key=upload_info.folder_key, filedrop_key=upload_info.filedrop_key, path=upload_info.path, file_size=upload_info.size, file_hash=upload_info.hash_info.file, action_on_duplicate=upload_info.action_on_duplicate) logger.debug("upload_result: %s", upload_result) upload_key = upload_result['doupload']['key'] return self._poll_upload(upload_key, 'upload/simple')
Simple upload and return quickkey Can be used for small files smaller than UPLOAD_SIMPLE_LIMIT_BYTES upload_info -- UploadInfo object check_result -- ignored
entailment
def _upload_resumable_unit(self, uu_info): """Upload a single unit and return raw upload/resumable result uu_info -- UploadUnitInfo instance """ # Get actual unit size unit_size = uu_info.fd.len if uu_info.hash_ is None: raise ValueError('UploadUnitInfo.hash_ is now required') return self._api.upload_resumable( uu_info.fd, uu_info.upload_info.size, uu_info.upload_info.hash_info.file, uu_info.hash_, uu_info.uid, unit_size, filedrop_key=uu_info.upload_info.filedrop_key, folder_key=uu_info.upload_info.folder_key, path=uu_info.upload_info.path, action_on_duplicate=uu_info.upload_info.action_on_duplicate)
Upload a single unit and return raw upload/resumable result uu_info -- UploadUnitInfo instance
entailment
def _upload_resumable_all(self, upload_info, bitmap, number_of_units, unit_size): """Prepare and upload all resumable units and return upload_key upload_info -- UploadInfo object bitmap -- bitmap node of upload/check number_of_units -- number of units requested unit_size -- size of a single upload unit in bytes """ fd = upload_info.fd upload_key = None for unit_id in range(number_of_units): upload_status = decode_resumable_upload_bitmap( bitmap, number_of_units) if upload_status[unit_id]: logger.debug("Skipping unit %d/%d - already uploaded", unit_id + 1, number_of_units) continue logger.debug("Uploading unit %d/%d", unit_id + 1, number_of_units) offset = unit_id * unit_size with SubsetIO(fd, offset, unit_size) as unit_fd: unit_info = _UploadUnitInfo( upload_info=upload_info, hash_=upload_info.hash_info.units[unit_id], fd=unit_fd, uid=unit_id) upload_result = self._upload_resumable_unit(unit_info) # upload_key is needed for polling if upload_key is None: upload_key = upload_result['doupload']['key'] return upload_key
Prepare and upload all resumable units and return upload_key upload_info -- UploadInfo object bitmap -- bitmap node of upload/check number_of_units -- number of units requested unit_size -- size of a single upload unit in bytes
entailment
def _upload_resumable(self, upload_info, check_result): """Resumable upload and return quickkey upload_info -- UploadInfo object check_result -- dict of upload/check call result """ resumable_upload = check_result['resumable_upload'] unit_size = int(resumable_upload['unit_size']) number_of_units = int(resumable_upload['number_of_units']) # make sure we have calculated the right thing logger.debug("number_of_units=%s (expected %s)", number_of_units, len(upload_info.hash_info.units)) assert len(upload_info.hash_info.units) == number_of_units logger.debug("Preparing %d units * %d bytes", number_of_units, unit_size) upload_key = None retries = UPLOAD_RETRY_COUNT all_units_ready = resumable_upload['all_units_ready'] == 'yes' bitmap = resumable_upload['bitmap'] while not all_units_ready and retries > 0: upload_key = self._upload_resumable_all(upload_info, bitmap, number_of_units, unit_size) check_result = self._upload_check(upload_info, resumable=True) resumable_upload = check_result['resumable_upload'] all_units_ready = resumable_upload['all_units_ready'] == 'yes' bitmap = resumable_upload['bitmap'] if not all_units_ready: retries -= 1 logger.debug("Some units failed to upload (%d retries left)", retries) if not all_units_ready: # Most likely non-retriable raise UploadError("Could not upload all units") logger.debug("Upload complete, polling for status") return self._poll_upload(upload_key, 'upload/resumable')
Resumable upload and return quickkey upload_info -- UploadInfo object check_result -- dict of upload/check call result
entailment
def reset(self): """Remove from sys.modules the modules imported by the debuggee.""" if not self.hooked: self.hooked = True sys.path_hooks.append(self) sys.path.insert(0, self.PATH_ENTRY) return for modname in self: if modname in sys.modules: del sys.modules[modname] submods = [] for subm in sys.modules: if subm.startswith(modname + '.'): submods.append(subm) # All submodules of modname may not have been imported by the # debuggee, but they are still removed from sys.modules as # there is no way to distinguish them. for subm in submods: del sys.modules[subm] self[:] = []
Remove from sys.modules the modules imported by the debuggee.
entailment
def get_func_lno(self, funcname): """The first line number of the last defined 'funcname' function.""" class FuncLineno(ast.NodeVisitor): def __init__(self): self.clss = [] def generic_visit(self, node): for child in ast.iter_child_nodes(node): for item in self.visit(child): yield item def visit_ClassDef(self, node): self.clss.append(node.name) for item in self.generic_visit(node): yield item self.clss.pop() def visit_FunctionDef(self, node): # Only allow non nested function definitions. name = '.'.join(itertools.chain(self.clss, [node.name])) yield name, node.lineno if self.functions_firstlno is None: self.functions_firstlno = {} for name, lineno in FuncLineno().visit(self.node): if (name not in self.functions_firstlno or self.functions_firstlno[name] < lineno): self.functions_firstlno[name] = lineno try: return self.functions_firstlno[funcname] except KeyError: raise BdbSourceError('{}: function "{}" not found.'.format( self.filename, funcname))
The first line number of the last defined 'funcname' function.
entailment
def get_actual_bp(self, lineno): """Get the actual breakpoint line number. When an exact match cannot be found in the lnotab expansion of the module code object or one of its subcodes, pick up the next valid statement line number. Return the statement line defined by the tuple (code firstlineno, statement line number) which is at the shortest distance to line 'lineno' and greater or equal to 'lineno'. When 'lineno' is the first line number of a subcode, use its first statement line instead. """ def _distance(code, module_level=False): """The shortest distance to the next valid statement.""" subcodes = dict((c.co_firstlineno, c) for c in code.co_consts if isinstance(c, types.CodeType) and not c.co_name.startswith('<')) # Get the shortest distance to the subcode whose first line number # is the last to be less or equal to lineno. That is, find the # index of the first subcode whose first_lno is the first to be # strictly greater than lineno. subcode_dist = None subcodes_flnos = sorted(subcodes) idx = bisect(subcodes_flnos, lineno) if idx != 0: flno = subcodes_flnos[idx-1] subcode_dist = _distance(subcodes[flno]) # Check if lineno is a valid statement line number in the current # code, excluding function or method definition lines. code_lnos = sorted(code_line_numbers(code)) # Do not stop at execution of function definitions. if not module_level and len(code_lnos) > 1: code_lnos = code_lnos[1:] if lineno in code_lnos and lineno not in subcodes_flnos: return 0, (code.co_firstlineno, lineno) # Compute the distance to the next valid statement in this code. idx = bisect(code_lnos, lineno) if idx == len(code_lnos): # lineno is greater that all 'code' line numbers. return subcode_dist actual_lno = code_lnos[idx] dist = actual_lno - lineno if subcode_dist and subcode_dist[0] < dist: return subcode_dist if actual_lno not in subcodes_flnos: return dist, (code.co_firstlineno, actual_lno) else: # The actual line number is the line number of the first # statement of the subcode following lineno (recursively). return _distance(subcodes[actual_lno]) if self.code: code_dist = _distance(self.code, module_level=True) if not self.code or not code_dist: raise BdbSourceError('{}: line {} is after the last ' 'valid statement.'.format(self.filename, lineno)) return code_dist[1]
Get the actual breakpoint line number. When an exact match cannot be found in the lnotab expansion of the module code object or one of its subcodes, pick up the next valid statement line number. Return the statement line defined by the tuple (code firstlineno, statement line number) which is at the shortest distance to line 'lineno' and greater or equal to 'lineno'. When 'lineno' is the first line number of a subcode, use its first statement line instead.
entailment
def get_breakpoints(self, lineno): """Return the list of breakpoints set at lineno.""" try: firstlineno, actual_lno = self.bdb_module.get_actual_bp(lineno) except BdbSourceError: return [] if firstlineno not in self: return [] code_bps = self[firstlineno] if actual_lno not in code_bps: return [] return [bp for bp in sorted(code_bps[actual_lno], key=attrgetter('number')) if bp.line == lineno]
Return the list of breakpoints set at lineno.
entailment
def settrace(self, do_set): """Set or remove the trace function.""" if do_set: sys.settrace(self.trace_dispatch) else: sys.settrace(None)
Set or remove the trace function.
entailment
def restart(self): """Restart the debugger after source code changes.""" _module_finder.reset() linecache.checkcache() for module_bpts in self.breakpoints.values(): module_bpts.reset()
Restart the debugger after source code changes.
entailment
def set_until(self, frame, lineno=None): """Stop when the current line number in frame is greater than lineno or when returning from frame.""" if lineno is None: lineno = frame.f_lineno + 1 self._set_stopinfo(frame, lineno)
Stop when the current line number in frame is greater than lineno or when returning from frame.
entailment
def set_trace(self, frame=None): """Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame. """ # First disable tracing temporarily as set_trace() may be called while # tracing is in use. For example when called from a signal handler and # within a debugging session started with runcall(). self.settrace(False) if not frame: frame = sys._getframe().f_back frame.f_trace = self.trace_dispatch # Do not change botframe when the debuggee has been started from an # instance of Pdb with one of the family of run methods. self.reset(ignore_first_call_event=False, botframe=self.botframe) self.topframe = frame while frame: if frame is self.botframe: break botframe = frame frame = frame.f_back else: self.botframe = botframe # Must trace the bottom frame to disable tracing on termination, # see issue 13044. if not self.botframe.f_trace: self.botframe.f_trace = self.trace_dispatch self.settrace(True)
Start debugging from `frame`. If frame is not specified, debugging starts from caller's frame.
entailment
def process_hit_event(self, frame): """Return (stop_state, delete_temporary) at a breakpoint hit event.""" if not self.enabled: return False, False # Count every hit when breakpoint is enabled. self.hits += 1 # A conditional breakpoint. if self.cond: try: if not eval_(self.cond, frame.f_globals, frame.f_locals): return False, False except Exception: # If the breakpoint condition evaluation fails, the most # conservative thing is to stop on the breakpoint. Don't # delete temporary, as another hint to the user. return True, False if self.ignore > 0: self.ignore -= 1 return False, False return True, True
Return (stop_state, delete_temporary) at a breakpoint hit event.
entailment
def listdir(directory): """Returns list of nested files and directories for local directory by path :param directory: absolute or relative path to local directory :return: list nested of file or directory names """ file_names = list() for filename in os.listdir(directory): file_path = os.path.join(directory, filename) if os.path.isdir(file_path): filename = f'{filename}{os.path.sep}' file_names.append(filename) return file_names
Returns list of nested files and directories for local directory by path :param directory: absolute or relative path to local directory :return: list nested of file or directory names
entailment
def get_options(option_type, from_options): """Extract options for specified option type from all options :param option_type: the object of specified type of options :param from_options: all options dictionary :return: the dictionary of options for specified type, each option can be filled by value from all options dictionary or blank in case the option for specified type is not exist in all options dictionary """ _options = dict() for key in option_type.keys: key_with_prefix = f'{option_type.prefix}{key}' if key not in from_options and key_with_prefix not in from_options: _options[key] = '' elif key in from_options: _options[key] = from_options.get(key) else: _options[key] = from_options.get(key_with_prefix) return _options
Extract options for specified option type from all options :param option_type: the object of specified type of options :param from_options: all options dictionary :return: the dictionary of options for specified type, each option can be filled by value from all options dictionary or blank in case the option for specified type is not exist in all options dictionary
entailment
def get_headers(self, action, headers_ext=None): """Returns HTTP headers of specified WebDAV actions. :param action: the identifier of action. :param headers_ext: (optional) the addition headers list witch sgould be added to basic HTTP headers for the specified action. :return: the dictionary of headers for specified action. """ if action in Client.http_header: try: headers = Client.http_header[action].copy() except AttributeError: headers = Client.http_header[action][:] else: headers = list() if headers_ext: headers.extend(headers_ext) if self.webdav.token: webdav_token = f'Authorization: OAuth {self.webdav.token}' headers.append(webdav_token) return dict([map(lambda s: s.strip(), i.split(':')) for i in headers])
Returns HTTP headers of specified WebDAV actions. :param action: the identifier of action. :param headers_ext: (optional) the addition headers list witch sgould be added to basic HTTP headers for the specified action. :return: the dictionary of headers for specified action.
entailment
def execute_request(self, action, path, data=None, headers_ext=None): """Generate request to WebDAV server for specified action and path and execute it. :param action: the action for WebDAV server which should be executed. :param path: the path to resource for action :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`. :param headers_ext: (optional) the addition headers list witch should be added to basic HTTP headers for the specified action. :return: HTTP response of request. """ response = self.session.request( method=Client.requests[action], url=self.get_url(path), auth=self.webdav.auth, headers=self.get_headers(action, headers_ext), timeout=self.timeout, data=data ) if response.status_code == 507: raise NotEnoughSpace() if 499 < response.status_code < 600: raise ServerException(url=self.get_url(path), code=response.status_code, message=response.content) if response.status_code >= 400: raise ResponseErrorCode(url=self.get_url(path), code=response.status_code, message=response.content) return response
Generate request to WebDAV server for specified action and path and execute it. :param action: the action for WebDAV server which should be executed. :param path: the path to resource for action :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`. :param headers_ext: (optional) the addition headers list witch should be added to basic HTTP headers for the specified action. :return: HTTP response of request.
entailment
def valid(self): """Validates of WebDAV and proxy settings. :return: True in case settings are valid and False otherwise. """ return True if self.webdav.valid() and self.proxy.valid() else False
Validates of WebDAV and proxy settings. :return: True in case settings are valid and False otherwise.
entailment
def list(self, remote_path=root): """Returns list of nested files and directories for remote WebDAV directory by path. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: path to remote directory. :return: list of nested file or directory names. """ directory_urn = Urn(remote_path, directory=True) if directory_urn.path() != Client.root: if not self.check(directory_urn.path()): raise RemoteResourceNotFound(directory_urn.path()) response = self.execute_request(action='list', path=directory_urn.quote()) urns = WebDavXmlUtils.parse_get_list_response(response.content) path = Urn.normalize_path(self.get_full_path(directory_urn)) return [urn.filename() for urn in urns if Urn.compare_path(path, urn.path()) is False]
Returns list of nested files and directories for remote WebDAV directory by path. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: path to remote directory. :return: list of nested file or directory names.
entailment
def free(self): """Returns an amount of free space on remote WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :return: an amount of free space in bytes. """ data = WebDavXmlUtils.create_free_space_request_content() response = self.execute_request(action='free', path='', data=data) return WebDavXmlUtils.parse_free_space_response(response.content, self.webdav.hostname)
Returns an amount of free space on remote WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :return: an amount of free space in bytes.
entailment
def check(self, remote_path=root): """Checks an existence of remote resource on WebDAV server by remote path. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: (optional) path to resource on WebDAV server. Defaults is root directory of WebDAV. :return: True if resource is exist or False otherwise """ urn = Urn(remote_path) try: response = self.execute_request(action='check', path=urn.quote()) except ResponseErrorCode: return False if int(response.status_code) == 200: return True return False
Checks an existence of remote resource on WebDAV server by remote path. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: (optional) path to resource on WebDAV server. Defaults is root directory of WebDAV. :return: True if resource is exist or False otherwise
entailment
def mkdir(self, remote_path): """Makes new directory on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MKCOL :param remote_path: path to directory :return: True if request executed with code 200 or 201 and False otherwise. """ directory_urn = Urn(remote_path, directory=True) try: response = self.execute_request(action='mkdir', path=directory_urn.quote()) return response.status_code in (200, 201) except ResponseErrorCode as e: if e.code == 405: return True raise
Makes new directory on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MKCOL :param remote_path: path to directory :return: True if request executed with code 200 or 201 and False otherwise.
entailment
def download_from(self, buff, remote_path): """Downloads file from WebDAV and writes it in buffer. :param buff: buffer object for writing of downloaded file content. :param remote_path: path to file on WebDAV server. """ urn = Urn(remote_path) if self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) response = self.execute_request(action='download', path=urn.quote()) buff.write(response.content)
Downloads file from WebDAV and writes it in buffer. :param buff: buffer object for writing of downloaded file content. :param remote_path: path to file on WebDAV server.
entailment
def download(self, remote_path, local_path, progress=None): """Downloads remote resource from WebDAV and save it in local path. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote resource for downloading can be file and directory. :param local_path: the path to save resource locally. :param progress: progress function. Not supported now. """ urn = Urn(remote_path) if self.is_dir(urn.path()): self.download_directory(local_path=local_path, remote_path=remote_path, progress=progress) else: self.download_file(local_path=local_path, remote_path=remote_path, progress=progress)
Downloads remote resource from WebDAV and save it in local path. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote resource for downloading can be file and directory. :param local_path: the path to save resource locally. :param progress: progress function. Not supported now.
entailment
def download_directory(self, remote_path, local_path, progress=None): """Downloads directory and downloads all nested files and directories from remote WebDAV to local. If there is something on local path it deletes directories and files then creates new. :param remote_path: the path to directory for downloading form WebDAV server. :param local_path: the path to local directory for saving downloaded files and directories. :param progress: Progress function. Not supported now. """ urn = Urn(remote_path, directory=True) if not self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if os.path.exists(local_path): shutil.rmtree(local_path) os.makedirs(local_path) for resource_name in self.list(urn.path()): _remote_path = f'{urn.path()}{resource_name}' _local_path = os.path.join(local_path, resource_name) self.download(local_path=_local_path, remote_path=_remote_path, progress=progress)
Downloads directory and downloads all nested files and directories from remote WebDAV to local. If there is something on local path it deletes directories and files then creates new. :param remote_path: the path to directory for downloading form WebDAV server. :param local_path: the path to local directory for saving downloaded files and directories. :param progress: Progress function. Not supported now.
entailment
def open(self, file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None): """Downloads file from WebDAV server and saves it temprorary, then opens it for further manipulations. Has the same interface as built-in open() :param file: the path to remote file for opening. """ urn = Urn(file) urn_path = urn.path() remote_file_exists = self.check(urn_path) if not remote_file_exists: if 'r' in mode: raise RemoteResourceNotFound(urn_path) elif self.is_dir(urn_path): raise OptionNotValid(name='file', value=file) with tempfile.TemporaryDirectory() as temp_dir: local_path = f'{temp_dir}{os.path.sep}{file}' if remote_file_exists: self.download_file(file, local_path) else: if ('w' in mode or 'a' in mode or 'x' in mode) and os.path.sep in local_path: os.makedirs(local_path.rsplit(os.path.sep, 1)[0], exist_ok=True) with open(file=local_path, mode=mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline, closefd=closefd, opener=opener) as f: yield f if 'w' in mode or 'a' in mode or 'x' in mode: self.upload_file(file, local_path)
Downloads file from WebDAV server and saves it temprorary, then opens it for further manipulations. Has the same interface as built-in open() :param file: the path to remote file for opening.
entailment
def download_file(self, remote_path, local_path, progress=None): """Downloads file from WebDAV server and save it locally. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote file for downloading. :param local_path: the path to save file locally. :param progress: progress function. Not supported now. """ urn = Urn(remote_path) if self.is_dir(urn.path()): raise OptionNotValid(name='remote_path', value=remote_path) if os.path.isdir(local_path): raise OptionNotValid(name='local_path', value=local_path) if os.path.sep in local_path: os.makedirs(local_path.rsplit(os.path.sep, 1)[0], exist_ok=True) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) with open(local_path, 'wb') as local_file: response = self.execute_request('download', urn.quote()) for block in response.iter_content(1024): local_file.write(block)
Downloads file from WebDAV server and save it locally. More information you can find by link http://webdav.org/specs/rfc4918.html#rfc.section.9.4 :param remote_path: the path to remote file for downloading. :param local_path: the path to save file locally. :param progress: progress function. Not supported now.
entailment
def download_sync(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server synchronously. :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete. """ self.download(local_path=local_path, remote_path=remote_path) if callback: callback()
Downloads remote resources from WebDAV server synchronously. :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete.
entailment
def download_async(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server asynchronously :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete. """ target = (lambda: self.download_sync(local_path=local_path, remote_path=remote_path, callback=callback)) threading.Thread(target=target).start()
Downloads remote resources from WebDAV server asynchronously :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete.
entailment
def upload_to(self, buff, remote_path): """Uploads file from buffer to remote path on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param buff: the buffer with content for file. :param remote_path: the path to save file remotely on WebDAV server. """ urn = Urn(remote_path) if urn.is_dir(): raise OptionNotValid(name='remote_path', value=remote_path) if not self.check(urn.parent()): raise RemoteParentNotFound(urn.path()) self.execute_request(action='upload', path=urn.quote(), data=buff)
Uploads file from buffer to remote path on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param buff: the buffer with content for file. :param remote_path: the path to save file remotely on WebDAV server.
entailment
def upload(self, remote_path, local_path, progress=None): """Uploads resource to remote path on WebDAV server. In case resource is directory it will upload all nested files and directories. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param progress: Progress function. Not supported now. """ if os.path.isdir(local_path): self.upload_directory(local_path=local_path, remote_path=remote_path, progress=progress) else: self.upload_file(local_path=local_path, remote_path=remote_path)
Uploads resource to remote path on WebDAV server. In case resource is directory it will upload all nested files and directories. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param progress: Progress function. Not supported now.
entailment
def upload_directory(self, remote_path, local_path, progress=None): """Uploads directory to remote path on WebDAV server. In case directory is exist on remote server it will delete it and then upload directory with nested files and directories. :param remote_path: the path to directory for uploading on WebDAV server. :param local_path: the path to local directory for uploading. :param progress: Progress function. Not supported now. """ urn = Urn(remote_path, directory=True) if not urn.is_dir(): raise OptionNotValid(name='remote_path', value=remote_path) if not os.path.isdir(local_path): raise OptionNotValid(name='local_path', value=local_path) if not os.path.exists(local_path): raise LocalResourceNotFound(local_path) if self.check(urn.path()): self.clean(urn.path()) self.mkdir(remote_path) for resource_name in listdir(local_path): _remote_path = f'{urn.path()}{resource_name}' _local_path = os.path.join(local_path, resource_name) self.upload(local_path=_local_path, remote_path=_remote_path, progress=progress)
Uploads directory to remote path on WebDAV server. In case directory is exist on remote server it will delete it and then upload directory with nested files and directories. :param remote_path: the path to directory for uploading on WebDAV server. :param local_path: the path to local directory for uploading. :param progress: Progress function. Not supported now.
entailment
def upload_file(self, remote_path, local_path, progress=None): """Uploads file to remote path on WebDAV server. File should be 2Gb or less. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param remote_path: the path to uploading file on WebDAV server. :param local_path: the path to local file for uploading. :param progress: Progress function. Not supported now. """ if not os.path.exists(local_path): raise LocalResourceNotFound(local_path) urn = Urn(remote_path) if urn.is_dir(): raise OptionNotValid(name='remote_path', value=remote_path) if os.path.isdir(local_path): raise OptionNotValid(name='local_path', value=local_path) if not self.check(urn.parent()): raise RemoteParentNotFound(urn.path()) with open(local_path, 'rb') as local_file: file_size = os.path.getsize(local_path) if file_size > self.large_size: raise ResourceTooBig(path=local_path, size=file_size, max_size=self.large_size) self.execute_request(action='upload', path=urn.quote(), data=local_file)
Uploads file to remote path on WebDAV server. File should be 2Gb or less. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PUT :param remote_path: the path to uploading file on WebDAV server. :param local_path: the path to local file for uploading. :param progress: Progress function. Not supported now.
entailment
def upload_sync(self, remote_path, local_path, callback=None): """Uploads resource to remote path on WebDAV server synchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete. """ self.upload(local_path=local_path, remote_path=remote_path) if callback: callback()
Uploads resource to remote path on WebDAV server synchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete.
entailment
def upload_async(self, remote_path, local_path, callback=None): """Uploads resource to remote path on WebDAV server asynchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete. """ target = (lambda: self.upload_sync(local_path=local_path, remote_path=remote_path, callback=callback)) threading.Thread(target=target).start()
Uploads resource to remote path on WebDAV server asynchronously. In case resource is directory it will upload all nested files and directories. :param remote_path: the path for uploading resources on WebDAV server. Can be file and directory. :param local_path: the path to local resource for uploading. :param callback: the callback which will be invoked when downloading is complete.
entailment
def copy(self, remote_path_from, remote_path_to): """Copies resource from one place to another on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_COPY :param remote_path_from: the path to resource which will be copied, :param remote_path_to: the path where resource will be copied. """ urn_from = Urn(remote_path_from) if not self.check(urn_from.path()): raise RemoteResourceNotFound(urn_from.path()) urn_to = Urn(remote_path_to) if not self.check(urn_to.parent()): raise RemoteParentNotFound(urn_to.path()) header_destination = f'Destination: {self.get_full_path(urn_to)}' self.execute_request(action='copy', path=urn_from.quote(), headers_ext=[header_destination])
Copies resource from one place to another on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_COPY :param remote_path_from: the path to resource which will be copied, :param remote_path_to: the path where resource will be copied.
entailment
def move(self, remote_path_from, remote_path_to, overwrite=False): """Moves resource from one place to another on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MOVE :param remote_path_from: the path to resource which will be moved, :param remote_path_to: the path where resource will be moved. :param overwrite: (optional) the flag, overwrite file if it exists. Defaults is False """ urn_from = Urn(remote_path_from) if not self.check(urn_from.path()): raise RemoteResourceNotFound(urn_from.path()) urn_to = Urn(remote_path_to) if not self.check(urn_to.parent()): raise RemoteParentNotFound(urn_to.path()) header_destination = f'Destination: {self.get_full_path(urn_to)}' header_overwrite = f'Overwrite: {"T" if overwrite else "F"}' self.execute_request(action='move', path=urn_from.quote(), headers_ext=[header_destination, header_overwrite])
Moves resource from one place to another on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_MOVE :param remote_path_from: the path to resource which will be moved, :param remote_path_to: the path where resource will be moved. :param overwrite: (optional) the flag, overwrite file if it exists. Defaults is False
entailment
def clean(self, remote_path): """Cleans (Deletes) a remote resource on WebDAV server. The name of method is not changed for back compatibility with original library. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_DELETE :param remote_path: the remote resource whisch will be deleted. """ urn = Urn(remote_path) self.execute_request(action='clean', path=urn.quote())
Cleans (Deletes) a remote resource on WebDAV server. The name of method is not changed for back compatibility with original library. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_DELETE :param remote_path: the remote resource whisch will be deleted.
entailment
def info(self, remote_path): """Gets information about resource on WebDAV. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: a dictionary of information attributes and them values with following keys: `created`: date of resource creation, `name`: name of resource, `size`: size of resource, `modified`: date of resource modification. """ urn = Urn(remote_path) if not self.check(urn.path()) and not self.check(Urn(remote_path, directory=True).path()): raise RemoteResourceNotFound(remote_path) response = self.execute_request(action='info', path=urn.quote()) path = self.get_full_path(urn) return WebDavXmlUtils.parse_info_response(content=response.content, path=path, hostname=self.webdav.hostname)
Gets information about resource on WebDAV. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: a dictionary of information attributes and them values with following keys: `created`: date of resource creation, `name`: name of resource, `size`: size of resource, `modified`: date of resource modification.
entailment
def is_dir(self, remote_path): """Checks is the remote resource directory. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: True in case the remote resource is directory and False otherwise. """ urn = Urn(remote_path) parent_urn = Urn(urn.parent()) if not self.check(urn.path()) and not self.check(Urn(remote_path, directory=True).path()): raise RemoteResourceNotFound(remote_path) response = self.execute_request(action='info', path=parent_urn.quote()) path = self.get_full_path(urn) return WebDavXmlUtils.parse_is_dir_response(content=response.content, path=path, hostname=self.webdav.hostname)
Checks is the remote resource directory. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :return: True in case the remote resource is directory and False otherwise.
entailment
def get_property(self, remote_path, option): """Gets metadata property of remote resource on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :param option: the property attribute as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set. :return: the value of property or None if property is not found. """ urn = Urn(remote_path) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) data = WebDavXmlUtils.create_get_property_request_content(option) response = self.execute_request(action='get_property', path=urn.quote(), data=data) return WebDavXmlUtils.parse_get_property_response(response.content, option['name'])
Gets metadata property of remote resource on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPFIND :param remote_path: the path to remote resource. :param option: the property attribute as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set. :return: the value of property or None if property is not found.
entailment
def set_property(self, remote_path, option): """Sets metadata property of remote resource on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPPATCH :param remote_path: the path to remote resource. :param option: the property attribute as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. """ self.set_property_batch(remote_path=remote_path, option=[option])
Sets metadata property of remote resource on WebDAV server. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPPATCH :param remote_path: the path to remote resource. :param option: the property attribute as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string.
entailment
def set_property_batch(self, remote_path, option): """Sets batch metadata properties of remote resource on WebDAV server in batch. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPPATCH :param remote_path: the path to remote resource. :param option: the property attributes as list of dictionaries with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. """ urn = Urn(remote_path) if not self.check(urn.path()): raise RemoteResourceNotFound(urn.path()) data = WebDavXmlUtils.create_set_property_batch_request_content(option) self.execute_request(action='set_property', path=urn.quote(), data=data)
Sets batch metadata properties of remote resource on WebDAV server in batch. More information you can find by link http://webdav.org/specs/rfc4918.html#METHOD_PROPPATCH :param remote_path: the path to remote resource. :param option: the property attributes as list of dictionaries with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string.
entailment
def parse_get_list_response(content): """Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path. :return: list of extracted file or directory names. """ try: tree = etree.fromstring(content) hrees = [Urn.separate + unquote(urlsplit(hree.text).path) for hree in tree.findall('.//{DAV:}href')] return [Urn(hree) for hree in hrees] except etree.XMLSyntaxError: return list()
Parses of response content XML from WebDAV server and extract file and directory names. :param content: the XML content of HTTP response from WebDAV server for getting list of files by remote path. :return: list of extracted file or directory names.
entailment
def create_free_space_request_content(): """Creates an XML for requesting of free space on remote WebDAV server. :return: the XML string of request content. """ root = etree.Element('propfind', xmlns='DAV:') prop = etree.SubElement(root, 'prop') etree.SubElement(prop, 'quota-available-bytes') etree.SubElement(prop, 'quota-used-bytes') tree = etree.ElementTree(root) return WebDavXmlUtils.etree_to_string(tree)
Creates an XML for requesting of free space on remote WebDAV server. :return: the XML string of request content.
entailment
def parse_free_space_response(content, hostname): """Parses of response content XML from WebDAV server and extract an amount of free space. :param content: the XML content of HTTP response from WebDAV server for getting free space. :param hostname: the server hostname. :return: an amount of free space in bytes. """ try: tree = etree.fromstring(content) node = tree.find('.//{DAV:}quota-available-bytes') if node is not None: return int(node.text) else: raise MethodNotSupported(name='free', server=hostname) except TypeError: raise MethodNotSupported(name='free', server=hostname) except etree.XMLSyntaxError: return str()
Parses of response content XML from WebDAV server and extract an amount of free space. :param content: the XML content of HTTP response from WebDAV server for getting free space. :param hostname: the server hostname. :return: an amount of free space in bytes.
entailment
def parse_info_response(content, path, hostname): """Parses of response content XML from WebDAV server and extract an information about resource. :param content: the XML content of HTTP response from WebDAV server. :param path: the path to resource. :param hostname: the server hostname. :return: a dictionary of information attributes and them values with following keys: `created`: date of resource creation, `name`: name of resource, `size`: size of resource, `modified`: date of resource modification. """ response = WebDavXmlUtils.extract_response_for_path(content=content, path=path, hostname=hostname) find_attributes = { 'created': './/{DAV:}creationdate', 'name': './/{DAV:}displayname', 'size': './/{DAV:}getcontentlength', 'modified': './/{DAV:}getlastmodified' } info = dict() for (name, value) in find_attributes.items(): info[name] = response.findtext(value) return info
Parses of response content XML from WebDAV server and extract an information about resource. :param content: the XML content of HTTP response from WebDAV server. :param path: the path to resource. :param hostname: the server hostname. :return: a dictionary of information attributes and them values with following keys: `created`: date of resource creation, `name`: name of resource, `size`: size of resource, `modified`: date of resource modification.
entailment
def parse_is_dir_response(content, path, hostname): """Parses of response content XML from WebDAV server and extract an information about resource. :param content: the XML content of HTTP response from WebDAV server. :param path: the path to resource. :param hostname: the server hostname. :return: True in case the remote resource is directory and False otherwise. """ response = WebDavXmlUtils.extract_response_for_path(content=content, path=path, hostname=hostname) resource_type = response.find('.//{DAV:}resourcetype') if resource_type is None: raise MethodNotSupported(name='is_dir', server=hostname) dir_type = resource_type.find('{DAV:}collection') return dir_type is not None
Parses of response content XML from WebDAV server and extract an information about resource. :param content: the XML content of HTTP response from WebDAV server. :param path: the path to resource. :param hostname: the server hostname. :return: True in case the remote resource is directory and False otherwise.
entailment
def create_get_property_request_content(option): """Creates an XML for requesting of getting a property value of remote WebDAV resource. :param option: the property attributes as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be get, `name`: the name of property which will be get. :return: the XML string of request content. """ root = etree.Element('propfind', xmlns='DAV:') prop = etree.SubElement(root, 'prop') etree.SubElement(prop, option.get('name', ''), xmlns=option.get('namespace', '')) tree = etree.ElementTree(root) return WebDavXmlUtils.etree_to_string(tree)
Creates an XML for requesting of getting a property value of remote WebDAV resource. :param option: the property attributes as dictionary with following keys: `namespace`: (optional) the namespace for XML property which will be get, `name`: the name of property which will be get. :return: the XML string of request content.
entailment
def parse_get_property_response(content, name): """Parses of response content XML from WebDAV server for getting metadata property value for some resource. :param content: the XML content of response as string. :param name: the name of property for finding a value in response :return: the value of property if it has been found or None otherwise. """ tree = etree.fromstring(content) return tree.xpath('//*[local-name() = $name]', name=name)[0].text
Parses of response content XML from WebDAV server for getting metadata property value for some resource. :param content: the XML content of response as string. :param name: the name of property for finding a value in response :return: the value of property if it has been found or None otherwise.
entailment
def create_set_property_batch_request_content(options): """Creates an XML for requesting of setting a property values for remote WebDAV resource in batch. :param options: the property attributes as list of dictionaries with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. :return: the XML string of request content. """ root_node = etree.Element('propertyupdate', xmlns='DAV:') set_node = etree.SubElement(root_node, 'set') prop_node = etree.SubElement(set_node, 'prop') for option in options: opt_node = etree.SubElement(prop_node, option['name'], xmlns=option.get('namespace', '')) opt_node.text = option.get('value', '') tree = etree.ElementTree(root_node) return WebDavXmlUtils.etree_to_string(tree)
Creates an XML for requesting of setting a property values for remote WebDAV resource in batch. :param options: the property attributes as list of dictionaries with following keys: `namespace`: (optional) the namespace for XML property which will be set, `name`: the name of property which will be set, `value`: (optional) the value of property which will be set. Defaults is empty string. :return: the XML string of request content.
entailment
def etree_to_string(tree): """Creates string from lxml.etree.ElementTree with XML declaration and UTF-8 encoding. :param tree: the instance of ElementTree :return: the string of XML. """ buff = BytesIO() tree.write(buff, xml_declaration=True, encoding='UTF-8') return buff.getvalue()
Creates string from lxml.etree.ElementTree with XML declaration and UTF-8 encoding. :param tree: the instance of ElementTree :return: the string of XML.
entailment
def extract_response_for_path(content, path, hostname): """Extracts single response for specified remote resource. :param content: raw content of response as string. :param path: the path to needed remote resource. :param hostname: the server hostname. :return: XML object of response for the remote resource defined by path. """ try: tree = etree.fromstring(content) responses = tree.findall('{DAV:}response') n_path = Urn.normalize_path(path) for resp in responses: href = resp.findtext('{DAV:}href') if Urn.compare_path(n_path, href) is True: return resp raise RemoteResourceNotFound(path) except etree.XMLSyntaxError: raise MethodNotSupported(name='is_dir', server=hostname)
Extracts single response for specified remote resource. :param content: raw content of response as string. :param path: the path to needed remote resource. :param hostname: the server hostname. :return: XML object of response for the remote resource defined by path.
entailment
def cleanup(config_dir): """Remove temporary stderr and stdout files as well as the daemon socket.""" stdout_path = os.path.join(config_dir, 'pueue.stdout') stderr_path = os.path.join(config_dir, 'pueue.stderr') if os._exists(stdout_path): os.remove(stdout_path) if os._exists(stderr_path): os.remove(stderr_path) socketPath = os.path.join(config_dir, 'pueue.sock') if os.path.exists(socketPath): os.remove(socketPath)
Remove temporary stderr and stdout files as well as the daemon socket.
entailment
def get_descriptor_output(descriptor, key, handler=None): """Get the descriptor output and handle incorrect UTF-8 encoding of subprocess logs. In case an process contains valid UTF-8 lines as well as invalid lines, we want to preserve the valid and remove the invalid ones. To do this we need to get each line and check for an UnicodeDecodeError. """ line = 'stub' lines = '' while line != '': try: line = descriptor.readline() lines += line except UnicodeDecodeError: error_msg = "Error while decoding output of process {}".format(key) if handler: handler.logger.error("{} with command {}".format( error_msg, handler.queue[key]['command'])) lines += error_msg + '\n' return lines.replace('\n', '\n ')
Get the descriptor output and handle incorrect UTF-8 encoding of subprocess logs. In case an process contains valid UTF-8 lines as well as invalid lines, we want to preserve the valid and remove the invalid ones. To do this we need to get each line and check for an UnicodeDecodeError.
entailment
def request(self, hash_, quickkey, doc_type, page=None, output=None, size_id=None, metadata=None, request_conversion_only=None): """Query conversion server hash_: 4 characters of file hash quickkey: File quickkey doc_type: "i" for image, "d" for documents page: The page to convert. If page is set to 'initial', the first 10 pages of the document will be provided. (document) output: "pdf", "img", or "swf" (document) size_id: 0,1,2 (document) 0-9, a-f, z (image) metadata: Set to 1 to get metadata dict request_conversion_only: Request conversion w/o content """ if len(hash_) > 4: hash_ = hash_[:4] query = QueryParams({ 'quickkey': quickkey, 'doc_type': doc_type, 'page': page, 'output': output, 'size_id': size_id, 'metadata': metadata, 'request_conversion_only': request_conversion_only }) url = API_ENDPOINT + '?' + hash_ + '&' + urlencode(query) response = self.http.get(url, stream=True) if response.status_code == 204: raise ConversionServerError("Unable to fulfill request. " "The document will not be converted.", response.status_code) response.raise_for_status() if response.headers['content-type'] == 'application/json': return response.json() return response
Query conversion server hash_: 4 characters of file hash quickkey: File quickkey doc_type: "i" for image, "d" for documents page: The page to convert. If page is set to 'initial', the first 10 pages of the document will be provided. (document) output: "pdf", "img", or "swf" (document) size_id: 0,1,2 (document) 0-9, a-f, z (image) metadata: Set to 1 to get metadata dict request_conversion_only: Request conversion w/o content
entailment
def user_method(user_event): """Decorator of the Pdb user_* methods that controls the RemoteSocket.""" def wrapper(self, *args): stdin = self.stdin is_sock = isinstance(stdin, RemoteSocket) try: try: if is_sock and not stdin.connect(): return return user_event(self, *args) except Exception: self.close() raise finally: if is_sock and stdin.closed(): self.do_detach(None) return wrapper
Decorator of the Pdb user_* methods that controls the RemoteSocket.
entailment
def user_line(self, frame, breakpoint_hits=None): """This function is called when we stop or break at this line.""" if not breakpoint_hits: self.interaction(frame, None) else: commands_result = self.bp_commands(frame, breakpoint_hits) if not commands_result: self.interaction(frame, None) else: doprompt, silent = commands_result if not silent: self.print_stack_entry(self.stack[self.curindex]) if doprompt: self._cmdloop() self.forget()
This function is called when we stop or break at this line.
entailment
def bp_commands(self, frame, breakpoint_hits): """Call every command that was set for the current active breakpoints. Returns True if the normal interaction function must be called, False otherwise.""" # Handle multiple breakpoints on the same line (issue 14789) effective_bp_list, temporaries = breakpoint_hits silent = True doprompt = False atleast_one_cmd = False for bp in effective_bp_list: if bp in self.commands: if not atleast_one_cmd: atleast_one_cmd = True self.setup(frame, None) lastcmd_back = self.lastcmd for line in self.commands[bp]: self.onecmd(line) self.lastcmd = lastcmd_back if not self.commands_silent[bp]: silent = False if self.commands_doprompt[bp]: doprompt = True # Delete the temporary breakpoints. tmp_to_delete = ' '.join(str(bp) for bp in temporaries) if tmp_to_delete: self.do_clear(tmp_to_delete) if atleast_one_cmd: return doprompt, silent return None
Call every command that was set for the current active breakpoints. Returns True if the normal interaction function must be called, False otherwise.
entailment
def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" frame.f_locals['__return__'] = return_value self.message('--Return--') self.interaction(frame, None)
This function is called when a return trap is set here.
entailment
def user_exception(self, frame, exc_info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" exc_type, exc_value, exc_traceback = exc_info frame.f_locals['__exception__'] = exc_type, exc_value # An 'Internal StopIteration' exception is an exception debug event # issued by the interpreter when handling a subgenerator run with # 'yield from' or a generator controled by a for loop. No exception has # actually occured in this case. The debugger uses this debug event to # stop when the debuggee is returning from such generators. prefix = 'Internal ' if (PY34 and not exc_traceback and exc_type is StopIteration) else '' self.message('--Exception--\n%s%s' % (prefix, traceback.format_exception_only(exc_type, exc_value)[-1].strip())) self.interaction(frame, exc_traceback)
This function is called if an exception occurs, but only if we are to stop at or just below this level.
entailment
def precmd(self, line): """Handle alias expansion and ';;' separator.""" if not line.strip(): return line args = line.split() while args[0] in self.aliases: line = self.aliases[args[0]] ii = 1 for tmpArg in args[1:]: line = line.replace("%" + str(ii), tmpArg) ii += 1 line = line.replace("%*", ' '.join(args[1:])) args = line.split() # split into ';;' separated commands # unless it's an alias command if args[0] != 'alias': marker = line.find(';;') if marker >= 0: # queue up everything after marker next = line[marker+2:].lstrip() self.cmdqueue.append(next) line = line[:marker].rstrip() return line
Handle alias expansion and ';;' separator.
entailment
def onecmd(self, line): """Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt or in a breakpoint command list definition. """ if not self.commands_defining: return cmd.Cmd.onecmd(self, line) else: return self.handle_command_def(line)
Interpret the argument as though it had been typed in response to the prompt. Checks whether this line is typed at the normal prompt or in a breakpoint command list definition.
entailment
def handle_command_def(self, line): """Handles one command line during command list definition.""" cmd, arg, line = self.parseline(line) if not cmd: return if cmd == 'silent': self.commands_silent[self.commands_bnum] = True return # continue to handle other cmd def in the cmd list elif cmd == 'end': self.cmdqueue = [] return 1 # end of cmd list cmdlist = self.commands[self.commands_bnum] if arg: cmdlist.append(cmd+' '+arg) else: cmdlist.append(cmd) # Determine if we must stop try: func = getattr(self, 'do_' + cmd) except AttributeError: func = self.default # one of the resuming commands if func.__name__ in self.commands_resuming: self.commands_doprompt[self.commands_bnum] = False self.cmdqueue = [] return 1 return
Handles one command line during command list definition.
entailment
def do_commands(self, arg): """commands [bpnumber] (com) ... (com) end (Pdb) Specify a list of commands for breakpoint number bpnumber. The commands themselves are entered on the following lines. Type a line containing just 'end' to terminate the commands. The commands are executed when the breakpoint is hit. To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands. With no bpnumber argument, commands refers to the last breakpoint set. You can use breakpoint commands to start your program up again. Simply use the continue command, or step, or any other command that resumes execution. Specifying any command resuming execution (currently continue, step, next, return, jump, quit and their abbreviations) terminates the command list (as if that command was immediately followed by end). This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint -- which could have its own command list, leading to ambiguities about which list to execute. If you use the 'silent' command in the command list, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the other commands print anything, you will see no sign that the breakpoint was reached. """ if not arg: bnum = len(bdb.Breakpoint.bpbynumber) - 1 else: try: bnum = int(arg) except Exception: self.error("Usage: commands [bnum]\n ...\n end") return self.commands_bnum = bnum # Save old definitions for the case of a keyboard interrupt. if bnum in self.commands: old_command_defs = (self.commands[bnum], self.commands_doprompt[bnum], self.commands_silent[bnum]) else: old_command_defs = None self.commands[bnum] = [] self.commands_doprompt[bnum] = True self.commands_silent[bnum] = False prompt_back = self.prompt self.prompt = '(com) ' self.commands_defining = True try: self.cmdloop() except KeyboardInterrupt: # Restore old definitions. if old_command_defs: self.commands[bnum] = old_command_defs[0] self.commands_doprompt[bnum] = old_command_defs[1] self.commands_silent[bnum] = old_command_defs[2] else: del self.commands[bnum] del self.commands_doprompt[bnum] del self.commands_silent[bnum] self.error('command definition aborted, old commands restored') finally: self.commands_defining = False self.prompt = prompt_back
commands [bpnumber] (com) ... (com) end (Pdb) Specify a list of commands for breakpoint number bpnumber. The commands themselves are entered on the following lines. Type a line containing just 'end' to terminate the commands. The commands are executed when the breakpoint is hit. To remove all commands from a breakpoint, type commands and follow it immediately with end; that is, give no commands. With no bpnumber argument, commands refers to the last breakpoint set. You can use breakpoint commands to start your program up again. Simply use the continue command, or step, or any other command that resumes execution. Specifying any command resuming execution (currently continue, step, next, return, jump, quit and their abbreviations) terminates the command list (as if that command was immediately followed by end). This is because any time you resume execution (even with a simple next or step), you may encounter another breakpoint -- which could have its own command list, leading to ambiguities about which list to execute. If you use the 'silent' command in the command list, the usual message about stopping at a breakpoint is not printed. This may be desirable for breakpoints that are to print a specific message and then continue. If none of the other commands print anything, you will see no sign that the breakpoint was reached.
entailment
def do_break(self, arg, temporary = 0): """b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks. With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of that function. If a second argument is present, it is a string specifying an expression which must evaluate to true before the breakpoint is honored. The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn't been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted. """ if not arg: all_breaks = '\n'.join(bp.bpformat() for bp in bdb.Breakpoint.bpbynumber if bp) if all_breaks: self.message("Num Type Disp Enb Where") self.message(all_breaks) return # Parse arguments, comma has lowest precedence and cannot occur in # filename. args = arg.rsplit(',', 1) cond = args[1].strip() if len(args) == 2 else None # Parse stuff before comma: [filename:]lineno | function. args = args[0].rsplit(':', 1) name = args[0].strip() lineno = args[1] if len(args) == 2 else args[0] try: lineno = int(lineno) except ValueError: if len(args) == 2: self.error('Bad lineno: "{}".'.format(lineno)) else: # Attempt the list of possible function or method fully # qualified names and corresponding filenames. candidates = get_fqn_fname(name, self.curframe) for fqn, fname in candidates: try: bp = self.set_break(fname, None, temporary, cond, fqn) self.message('Breakpoint {:d} at {}:{:d}'.format( bp.number, bp.file, bp.line)) return except bdb.BdbError: pass if not candidates: self.error( 'Not a function or a built-in: "{}"'.format(name)) else: self.error('Bad name: "{}".'.format(name)) else: filename = self.curframe.f_code.co_filename if len(args) == 2 and name: filename = name if filename.startswith('<') and filename.endswith('>'): # allow <doctest name>: doctest installs a hook at # linecache.getlines to allow <doctest name> to be # linecached and readable. if filename == '<string>' and self.mainpyfile: filename = self.mainpyfile else: root, ext = os.path.splitext(filename) if ext == '': filename = filename + '.py' if not os.path.exists(filename): self.error('Bad filename: "{}".'.format(arg)) return try: bp = self.set_break(filename, lineno, temporary, cond) except bdb.BdbError as err: self.error(err) else: self.message('Breakpoint {:d} at {}:{:d}'.format( bp.number, bp.file, bp.line))
b(reak) [ ([filename:]lineno | function) [, condition] ] Without argument, list all breaks. With a line number argument, set a break at this line in the current file. With a function name, set a break at the first executable line of that function. If a second argument is present, it is a string specifying an expression which must evaluate to true before the breakpoint is honored. The line number may be prefixed with a filename and a colon, to specify a breakpoint in another file (probably one that hasn't been loaded yet). The file is searched for on sys.path; the .py suffix may be omitted.
entailment
def defaultFile(self): """Produce a reasonable default.""" filename = self.curframe.f_code.co_filename if filename == '<string>' and self.mainpyfile: filename = self.mainpyfile return filename
Produce a reasonable default.
entailment
def do_enable(self, arg): """enable bpnumber [bpnumber ...] Enables the breakpoints given as a space separated list of breakpoint numbers. """ args = arg.split() for i in args: try: bp = self.get_bpbynumber(i) except ValueError as err: self.error(err) else: bp.enable() self.done_breakpoint_state(bp, True)
enable bpnumber [bpnumber ...] Enables the breakpoints given as a space separated list of breakpoint numbers.
entailment
def do_disable(self, arg): """disable bpnumber [bpnumber ...] Disables the breakpoints given as a space separated list of breakpoint numbers. Disabling a breakpoint means it cannot cause the program to stop execution, but unlike clearing a breakpoint, it remains in the list of breakpoints and can be (re-)enabled. """ args = arg.split() for i in args: try: bp = self.get_bpbynumber(i) except ValueError as err: self.error(err) else: bp.disable() self.done_breakpoint_state(bp, False)
disable bpnumber [bpnumber ...] Disables the breakpoints given as a space separated list of breakpoint numbers. Disabling a breakpoint means it cannot cause the program to stop execution, but unlike clearing a breakpoint, it remains in the list of breakpoints and can be (re-)enabled.
entailment
def do_condition(self, arg): """condition bpnumber [condition] Set a new condition for the breakpoint, an expression which must evaluate to true before the breakpoint is honored. If condition is absent, any existing condition is removed; i.e., the breakpoint is made unconditional. """ args = arg.split(' ', 1) try: cond = args[1] except IndexError: cond = None try: bp = self.get_bpbynumber(args[0].strip()) except IndexError: self.error('Breakpoint number expected') except ValueError as err: self.error(err) else: bp.cond = cond if not cond: self.message('Breakpoint %d is now unconditional.' % bp.number) else: self.message('New condition set for breakpoint %d.' % bp.number)
condition bpnumber [condition] Set a new condition for the breakpoint, an expression which must evaluate to true before the breakpoint is honored. If condition is absent, any existing condition is removed; i.e., the breakpoint is made unconditional.
entailment
def do_ignore(self, arg): """ignore bpnumber [count] Set the ignore count for the given breakpoint number. If count is omitted, the ignore count is set to 0. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates to true. """ args = arg.split(' ', 1) try: count = int(args[1].strip()) except Exception: count = 0 try: bp = self.get_bpbynumber(args[0].strip()) except IndexError: self.error('Breakpoint number expected') except ValueError as err: self.error(err) else: bp.ignore = count if count > 0: if count > 1: countstr = '%d crossings' % count else: countstr = '1 crossing' self.message('Will ignore next %s of breakpoint %d.' % (countstr, bp.number)) else: self.message('Will stop next time breakpoint %d is reached.' % bp.number)
ignore bpnumber [count] Set the ignore count for the given breakpoint number. If count is omitted, the ignore count is set to 0. A breakpoint becomes active when the ignore count is zero. When non-zero, the count is decremented each time the breakpoint is reached and the breakpoint is not disabled and any associated condition evaluates to true.
entailment
def do_clear(self, arg): """cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]] With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation). With a filename:lineno argument, clear all breaks at that line in that file. """ if not arg: try: if PY3: reply = input('Clear all breaks? ') else: reply = raw_input('Clear all breaks? ') except EOFError: reply = 'no' reply = reply.strip().lower() if reply in ('y', 'yes'): bplist = [bp for bp in bdb.Breakpoint.bpbynumber if bp] self.clear_all_breaks() for bp in bplist: self.done_delete_breakpoint(bp) return if ':' in arg: # Make sure it works for "clear C:\foo\bar.py:12" i = arg.rfind(':') filename = arg[:i] arg = arg[i+1:] try: lineno = int(arg) except ValueError: err = "Invalid line number (%s)" % arg else: bplist = self.get_breaks(filename, lineno) err = self.clear_break(filename, lineno) if err: self.error(err) else: for bp in bplist: self.done_delete_breakpoint(bp) return numberlist = arg.split() for i in numberlist: try: bp = self.get_bpbynumber(i) except ValueError as err: self.error(err) else: self.clear_bpbynumber(i) self.done_delete_breakpoint(bp)
cl(ear) filename:lineno\ncl(ear) [bpnumber [bpnumber...]] With a space separated list of breakpoint numbers, clear those breakpoints. Without argument, clear all breaks (but first ask confirmation). With a filename:lineno argument, clear all breaks at that line in that file.
entailment
def do_up(self, arg): """u(p) [count] Move the current frame count (default one) levels up in the stack trace (to an older frame). """ if self.curindex == 0: self.error('Oldest frame') return try: count = int(arg or 1) except ValueError: self.error('Invalid frame count (%s)' % arg) return if count < 0: newframe = 0 else: newframe = max(0, self.curindex - count) self._select_frame(newframe)
u(p) [count] Move the current frame count (default one) levels up in the stack trace (to an older frame).
entailment