idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
14,600 | def set_contents ( self , contents , encoding = None ) : self . encoding = encoding changed = self . _set_initial_contents ( contents ) if self . _side_effect is not None : self . _side_effect ( self ) return changed | Sets the file contents and size and increases the modification time . Also executes the side_effects if available . |
14,601 | def path ( self ) : names = [ ] obj = self while obj : names . insert ( 0 , obj . name ) obj = obj . parent_dir sep = self . filesystem . _path_separator ( self . name ) if names [ 0 ] == sep : names . pop ( 0 ) dir_path = sep . join ( names ) is_drive = names and len ( names [ 0 ] ) == 2 and names [ 0 ] [ 1 ] == ':' if not is_drive : dir_path = sep + dir_path else : dir_path = sep . join ( names ) dir_path = self . filesystem . absnormpath ( dir_path ) return dir_path | Return the full path of the current object . |
14,602 | def size ( self , st_size ) : self . _check_positive_int ( st_size ) current_size = self . st_size or 0 self . filesystem . change_disk_usage ( st_size - current_size , self . name , self . st_dev ) if self . _byte_contents : if st_size < current_size : self . _byte_contents = self . _byte_contents [ : st_size ] else : if IS_PY2 : self . _byte_contents = '%s%s' % ( self . _byte_contents , '\0' * ( st_size - current_size ) ) else : self . _byte_contents += b'\0' * ( st_size - current_size ) self . st_size = st_size self . epoch += 1 | Resizes file content padding with nulls if new size exceeds the old size . |
14,603 | def ordered_dirs ( self ) : return [ item [ 0 ] for item in sorted ( self . byte_contents . items ( ) , key = lambda entry : entry [ 1 ] . st_ino ) ] | Return the list of contained directory entry names ordered by creation order . |
14,604 | def add_entry ( self , path_object ) : if ( not is_root ( ) and not self . st_mode & PERM_WRITE and not self . filesystem . is_windows_fs ) : exception = IOError if IS_PY2 else OSError raise exception ( errno . EACCES , 'Permission Denied' , self . path ) if path_object . name in self . contents : self . filesystem . raise_os_error ( errno . EEXIST , self . path ) self . contents [ path_object . name ] = path_object path_object . parent_dir = self self . st_nlink += 1 path_object . st_nlink += 1 path_object . st_dev = self . st_dev if path_object . st_nlink == 1 : self . filesystem . change_disk_usage ( path_object . size , path_object . name , self . st_dev ) | Adds a child FakeFile to this directory . |
14,605 | def get_entry ( self , pathname_name ) : pathname_name = self . _normalized_entryname ( pathname_name ) return self . contents [ pathname_name ] | Retrieves the specified child file or directory entry . |
14,606 | def remove_entry ( self , pathname_name , recursive = True ) : pathname_name = self . _normalized_entryname ( pathname_name ) entry = self . get_entry ( pathname_name ) if self . filesystem . is_windows_fs : if entry . st_mode & PERM_WRITE == 0 : self . filesystem . raise_os_error ( errno . EACCES , pathname_name ) if self . filesystem . has_open_file ( entry ) : self . filesystem . raise_os_error ( errno . EACCES , pathname_name ) else : if ( not is_root ( ) and ( self . st_mode & ( PERM_WRITE | PERM_EXE ) != PERM_WRITE | PERM_EXE ) ) : self . filesystem . raise_os_error ( errno . EACCES , pathname_name ) if recursive and isinstance ( entry , FakeDirectory ) : while entry . contents : entry . remove_entry ( list ( entry . contents ) [ 0 ] ) elif entry . st_nlink == 1 : self . filesystem . change_disk_usage ( - entry . size , pathname_name , entry . st_dev ) self . st_nlink -= 1 entry . st_nlink -= 1 assert entry . st_nlink >= 0 del self . contents [ pathname_name ] | Removes the specified child file or directory . |
14,607 | def has_parent_object ( self , dir_object ) : obj = self while obj : if obj == dir_object : return True obj = obj . parent_dir return False | Return True if dir_object is a direct or indirect parent directory or if both are the same object . |
14,608 | def contents ( self ) : if not self . contents_read : self . contents_read = True base = self . path for entry in os . listdir ( self . source_path ) : source_path = os . path . join ( self . source_path , entry ) target_path = os . path . join ( base , entry ) if os . path . isdir ( source_path ) : self . filesystem . add_real_directory ( source_path , self . read_only , target_path = target_path ) else : self . filesystem . add_real_file ( source_path , self . read_only , target_path = target_path ) return self . byte_contents | Return the list of contained directory entries loading them if not already loaded . |
14,609 | def reset ( self , total_size = None ) : self . root = FakeDirectory ( self . path_separator , filesystem = self ) self . cwd = self . root . name self . open_files = [ ] self . _free_fd_heap = [ ] self . _last_ino = 0 self . _last_dev = 0 self . mount_points = { } self . add_mount_point ( self . root . name , total_size ) self . _add_standard_streams ( ) | Remove all file system contents and reset the root . |
14,610 | def raise_io_error ( self , errno , filename = None ) : raise IOError ( errno , self . _error_message ( errno ) , filename ) | Raises IOError . The error message is constructed from the given error code and shall start with the error in the real system . |
14,611 | def _matching_string ( matched , string ) : if string is None : return string if IS_PY2 : if isinstance ( matched , text_type ) : return text_type ( string ) else : if isinstance ( matched , bytes ) and isinstance ( string , str ) : return string . encode ( locale . getpreferredencoding ( False ) ) return string | Return the string as byte or unicode depending on the type of matched assuming string is an ASCII string . |
14,612 | def add_mount_point ( self , path , total_size = None ) : path = self . absnormpath ( path ) if path in self . mount_points : self . raise_os_error ( errno . EEXIST , path ) self . _last_dev += 1 self . mount_points [ path ] = { 'idev' : self . _last_dev , 'total_size' : total_size , 'used_size' : 0 } root_dir = ( self . root if path == self . root . name else self . create_dir ( path ) ) root_dir . st_dev = self . _last_dev return self . mount_points [ path ] | Add a new mount point for a filesystem device . The mount point gets a new unique device number . |
14,613 | def get_disk_usage ( self , path = None ) : DiskUsage = namedtuple ( 'usage' , 'total, used, free' ) if path is None : mount_point = self . mount_points [ self . root . name ] else : mount_point = self . _mount_point_for_path ( path ) if mount_point and mount_point [ 'total_size' ] is not None : return DiskUsage ( mount_point [ 'total_size' ] , mount_point [ 'used_size' ] , mount_point [ 'total_size' ] - mount_point [ 'used_size' ] ) return DiskUsage ( 1024 * 1024 * 1024 * 1024 , 0 , 1024 * 1024 * 1024 * 1024 ) | Return the total used and free disk space in bytes as named tuple or placeholder values simulating unlimited space if not set . |
14,614 | def change_disk_usage ( self , usage_change , file_path , st_dev ) : mount_point = self . _mount_point_for_device ( st_dev ) if mount_point : total_size = mount_point [ 'total_size' ] if total_size is not None : if total_size - mount_point [ 'used_size' ] < usage_change : self . raise_io_error ( errno . ENOSPC , file_path ) mount_point [ 'used_size' ] += usage_change | Change the used disk space by the given amount . |
14,615 | def _add_open_file ( self , file_obj ) : if self . _free_fd_heap : open_fd = heapq . heappop ( self . _free_fd_heap ) self . open_files [ open_fd ] = [ file_obj ] return open_fd self . open_files . append ( [ file_obj ] ) return len ( self . open_files ) - 1 | Add file_obj to the list of open files on the filesystem . Used internally to manage open files . |
14,616 | def _close_open_file ( self , file_des ) : self . open_files [ file_des ] = None heapq . heappush ( self . _free_fd_heap , file_des ) | Remove file object with given descriptor from the list of open files . |
14,617 | def get_open_file ( self , file_des ) : if not is_int_type ( file_des ) : raise TypeError ( 'an integer is required' ) if ( file_des >= len ( self . open_files ) or self . open_files [ file_des ] is None ) : self . raise_os_error ( errno . EBADF , str ( file_des ) ) return self . open_files [ file_des ] [ 0 ] | Return an open file . |
14,618 | def has_open_file ( self , file_object ) : return ( file_object in [ wrappers [ 0 ] . get_object ( ) for wrappers in self . open_files if wrappers ] ) | Return True if the given file object is in the list of open files . |
14,619 | def normpath ( self , path ) : path = self . normcase ( path ) drive , path = self . splitdrive ( path ) sep = self . _path_separator ( path ) is_absolute_path = path . startswith ( sep ) path_components = path . split ( sep ) collapsed_path_components = [ ] dot = self . _matching_string ( path , '.' ) dotdot = self . _matching_string ( path , '..' ) for component in path_components : if ( not component ) or ( component == dot ) : continue if component == dotdot : if collapsed_path_components and ( collapsed_path_components [ - 1 ] != dotdot ) : collapsed_path_components . pop ( ) continue elif is_absolute_path : continue collapsed_path_components . append ( component ) collapsed_path = sep . join ( collapsed_path_components ) if is_absolute_path : collapsed_path = sep + collapsed_path return drive + collapsed_path or dot | Mimic os . path . normpath using the specified path_separator . |
14,620 | def _original_path ( self , path ) : def components_to_path ( ) : if len ( path_components ) > len ( normalized_components ) : normalized_components . extend ( path_components [ len ( normalized_components ) : ] ) sep = self . _path_separator ( path ) normalized_path = sep . join ( normalized_components ) if path . startswith ( sep ) and not normalized_path . startswith ( sep ) : normalized_path = sep + normalized_path return normalized_path if self . is_case_sensitive or not path : return path path_components = self . _path_components ( path ) normalized_components = [ ] current_dir = self . root for component in path_components : if not isinstance ( current_dir , FakeDirectory ) : return components_to_path ( ) dir_name , current_dir = self . _directory_content ( current_dir , component ) if current_dir is None or ( isinstance ( current_dir , FakeDirectory ) and current_dir . _byte_contents is None and current_dir . st_size == 0 ) : return components_to_path ( ) normalized_components . append ( dir_name ) return components_to_path ( ) | Return a normalized case version of the given path for case - insensitive file systems . For case - sensitive file systems return path unchanged . |
14,621 | def absnormpath ( self , path ) : path = self . normcase ( path ) cwd = self . _matching_string ( path , self . cwd ) if not path : path = self . path_separator elif not self . _starts_with_root_path ( path ) : root_name = self . _matching_string ( path , self . root . name ) empty = self . _matching_string ( path , '' ) path = self . _path_separator ( path ) . join ( ( cwd != root_name and cwd or empty , path ) ) if path == self . _matching_string ( path , '.' ) : path = cwd return self . normpath ( path ) | Absolutize and minimalize the given path . |
14,622 | def splitpath ( self , path ) : path = self . normcase ( path ) sep = self . _path_separator ( path ) path_components = path . split ( sep ) if not path_components : return ( '' , '' ) starts_with_drive = self . _starts_with_drive_letter ( path ) basename = path_components . pop ( ) colon = self . _matching_string ( path , ':' ) if not path_components : if starts_with_drive : components = basename . split ( colon ) return ( components [ 0 ] + colon , components [ 1 ] ) return ( '' , basename ) for component in path_components : if component : while not path_components [ - 1 ] : path_components . pop ( ) if starts_with_drive : if not path_components : components = basename . split ( colon ) return ( components [ 0 ] + colon , components [ 1 ] ) if ( len ( path_components ) == 1 and path_components [ 0 ] . endswith ( colon ) ) : return ( path_components [ 0 ] + sep , basename ) return ( sep . join ( path_components ) , basename ) return ( sep , basename ) | Mimic os . path . splitpath using the specified path_separator . |
14,623 | def splitdrive ( self , path ) : path = make_string_path ( path ) if self . is_windows_fs : if len ( path ) >= 2 : path = self . normcase ( path ) sep = self . _path_separator ( path ) if sys . version_info >= ( 2 , 7 , 8 ) : if ( path [ 0 : 2 ] == sep * 2 ) and ( path [ 2 : 3 ] != sep ) : sep_index = path . find ( sep , 2 ) if sep_index == - 1 : return path [ : 0 ] , path sep_index2 = path . find ( sep , sep_index + 1 ) if sep_index2 == sep_index + 1 : return path [ : 0 ] , path if sep_index2 == - 1 : sep_index2 = len ( path ) return path [ : sep_index2 ] , path [ sep_index2 : ] if path [ 1 : 2 ] == self . _matching_string ( path , ':' ) : return path [ : 2 ] , path [ 2 : ] return path [ : 0 ] , path | Splits the path into the drive part and the rest of the path . |
14,624 | def joinpaths ( self , * paths ) : if sys . version_info >= ( 3 , 6 ) : paths = [ os . fspath ( path ) for path in paths ] if len ( paths ) == 1 : return paths [ 0 ] if self . is_windows_fs : return self . _join_paths_with_drive_support ( * paths ) joined_path_segments = [ ] sep = self . _path_separator ( paths [ 0 ] ) for path_segment in paths : if self . _starts_with_root_path ( path_segment ) : joined_path_segments = [ path_segment ] else : if ( joined_path_segments and not joined_path_segments [ - 1 ] . endswith ( sep ) ) : joined_path_segments . append ( sep ) if path_segment : joined_path_segments . append ( path_segment ) return self . _matching_string ( paths [ 0 ] , '' ) . join ( joined_path_segments ) | Mimic os . path . join using the specified path_separator . |
14,625 | def _path_components ( self , path ) : if not path or path == self . _path_separator ( path ) : return [ ] drive , path = self . splitdrive ( path ) path_components = path . split ( self . _path_separator ( path ) ) assert drive or path_components if not path_components [ 0 ] : if len ( path_components ) > 1 and not path_components [ 1 ] : path_components = [ ] else : path_components = path_components [ 1 : ] if drive : path_components . insert ( 0 , drive ) return path_components | Breaks the path into a list of component names . |
14,626 | def _starts_with_drive_letter ( self , file_path ) : colon = self . _matching_string ( file_path , ':' ) return ( self . is_windows_fs and len ( file_path ) >= 2 and file_path [ : 1 ] . isalpha and ( file_path [ 1 : 2 ] ) == colon ) | Return True if file_path starts with a drive letter . |
14,627 | def ends_with_path_separator ( self , file_path ) : if is_int_type ( file_path ) : return False file_path = make_string_path ( file_path ) return ( file_path and file_path not in ( self . path_separator , self . alternative_path_separator ) and ( file_path . endswith ( self . _path_separator ( file_path ) ) or self . alternative_path_separator is not None and file_path . endswith ( self . _alternative_path_separator ( file_path ) ) ) ) | Return True if file_path ends with a valid path separator . |
14,628 | def exists ( self , file_path , check_link = False ) : if check_link and self . islink ( file_path ) : return True file_path = make_string_path ( file_path ) if file_path is None : raise TypeError if not file_path : return False if file_path == self . dev_null . name : return not self . is_windows_fs try : if self . is_filepath_ending_with_separator ( file_path ) : return False file_path = self . resolve_path ( file_path ) except ( IOError , OSError ) : return False if file_path == self . root . name : return True path_components = self . _path_components ( file_path ) current_dir = self . root for component in path_components : current_dir = self . _directory_content ( current_dir , component ) [ 1 ] if not current_dir : return False return True | Return true if a path points to an existing file system object . |
14,629 | def resolve_path ( self , file_path , allow_fd = False , raw_io = True ) : if ( allow_fd and sys . version_info >= ( 3 , 3 ) and isinstance ( file_path , int ) ) : return self . get_open_file ( file_path ) . get_object ( ) . path file_path = make_string_path ( file_path ) if file_path is None : raise TypeError ( 'Expected file system path string, received None' ) file_path = self . _to_string ( file_path ) if not file_path or not self . _valid_relative_path ( file_path ) : self . raise_io_error ( errno . ENOENT , file_path ) file_path = self . absnormpath ( self . _original_path ( file_path ) ) if self . _is_root_path ( file_path ) : return file_path if file_path == self . dev_null . name : return file_path path_components = self . _path_components ( file_path ) resolved_components = self . _resolve_components ( path_components , raw_io ) return self . _components_to_path ( resolved_components ) | Follow a path resolving symlinks . |
14,630 | def _follow_link ( self , link_path_components , link ) : link_path = link . contents sep = self . _path_separator ( link_path ) if not self . _starts_with_root_path ( link_path ) : components = link_path_components [ : - 1 ] components . append ( link_path ) link_path = sep . join ( components ) return self . normpath ( link_path ) | Follow a link w . r . t . a path resolved so far . |
14,631 | def resolve ( self , file_path , follow_symlinks = True , allow_fd = False ) : if isinstance ( file_path , int ) : if allow_fd and sys . version_info >= ( 3 , 3 ) : return self . get_open_file ( file_path ) . get_object ( ) raise TypeError ( 'path should be string, bytes or ' 'os.PathLike (if supported), not int' ) if follow_symlinks : file_path = make_string_path ( file_path ) return self . get_object_from_normpath ( self . resolve_path ( file_path ) ) return self . lresolve ( file_path ) | Search for the specified filesystem object resolving all links . |
14,632 | def lresolve ( self , path ) : path = make_string_path ( path ) if path == self . root . name : return self . root path = self . _path_without_trailing_separators ( path ) path = self . _original_path ( path ) parent_directory , child_name = self . splitpath ( path ) if not parent_directory : parent_directory = self . cwd try : parent_obj = self . resolve ( parent_directory ) assert parent_obj if not isinstance ( parent_obj , FakeDirectory ) : if not self . is_windows_fs and isinstance ( parent_obj , FakeFile ) : self . raise_io_error ( errno . ENOTDIR , path ) self . raise_io_error ( errno . ENOENT , path ) return parent_obj . get_entry ( child_name ) except KeyError : self . raise_io_error ( errno . ENOENT , path ) | Search for the specified object resolving only parent links . |
14,633 | def add_object ( self , file_path , file_object , error_fct = None ) : error_fct = error_fct or self . raise_os_error if not file_path : target_directory = self . root else : target_directory = self . resolve ( file_path ) if not S_ISDIR ( target_directory . st_mode ) : error = errno . ENOENT if self . is_windows_fs else errno . ENOTDIR error_fct ( error , file_path ) target_directory . add_entry ( file_object ) | Add a fake file or directory into the filesystem at file_path . |
14,634 | def rename ( self , old_file_path , new_file_path , force_replace = False ) : ends_with_sep = self . ends_with_path_separator ( old_file_path ) old_file_path = self . absnormpath ( old_file_path ) new_file_path = self . absnormpath ( new_file_path ) if not self . exists ( old_file_path , check_link = True ) : self . raise_os_error ( errno . ENOENT , old_file_path , 2 ) if ends_with_sep : self . _handle_broken_link_with_trailing_sep ( old_file_path ) old_object = self . lresolve ( old_file_path ) if not self . is_windows_fs : self . _handle_posix_dir_link_errors ( new_file_path , old_file_path , ends_with_sep ) if self . exists ( new_file_path , check_link = True ) : new_file_path = self . _rename_to_existing_path ( force_replace , new_file_path , old_file_path , old_object , ends_with_sep ) if not new_file_path : return old_dir , old_name = self . splitpath ( old_file_path ) new_dir , new_name = self . splitpath ( new_file_path ) if not self . exists ( new_dir ) : self . raise_os_error ( errno . ENOENT , new_dir ) old_dir_object = self . resolve ( old_dir ) new_dir_object = self . resolve ( new_dir ) if old_dir_object . st_dev != new_dir_object . st_dev : self . raise_os_error ( errno . EXDEV , old_file_path ) if not S_ISDIR ( new_dir_object . st_mode ) : self . raise_os_error ( errno . EACCES if self . is_windows_fs else errno . ENOTDIR , new_file_path ) if new_dir_object . has_parent_object ( old_object ) : self . raise_os_error ( errno . EINVAL , new_file_path ) object_to_rename = old_dir_object . get_entry ( old_name ) old_dir_object . remove_entry ( old_name , recursive = False ) object_to_rename . name = new_name new_name = new_dir_object . _normalized_entryname ( new_name ) if new_name in new_dir_object . contents : new_dir_object . remove_entry ( new_name ) new_dir_object . add_entry ( object_to_rename ) | Renames a FakeFile object at old_file_path to new_file_path preserving all properties . |
14,635 | def remove_object ( self , file_path ) : file_path = self . absnormpath ( self . _original_path ( file_path ) ) if self . _is_root_path ( file_path ) : self . raise_os_error ( errno . EBUSY , file_path ) try : dirname , basename = self . splitpath ( file_path ) target_directory = self . resolve ( dirname ) target_directory . remove_entry ( basename ) except KeyError : self . raise_io_error ( errno . ENOENT , file_path ) except AttributeError : self . raise_io_error ( errno . ENOTDIR , file_path ) | Remove an existing file or directory . |
14,636 | def create_dir ( self , directory_path , perm_bits = PERM_DEF ) : directory_path = self . make_string_path ( directory_path ) directory_path = self . absnormpath ( directory_path ) self . _auto_mount_drive_if_needed ( directory_path ) if self . exists ( directory_path , check_link = True ) : self . raise_os_error ( errno . EEXIST , directory_path ) path_components = self . _path_components ( directory_path ) current_dir = self . root new_dirs = [ ] for component in path_components : directory = self . _directory_content ( current_dir , component ) [ 1 ] if not directory : new_dir = FakeDirectory ( component , filesystem = self ) new_dirs . append ( new_dir ) current_dir . add_entry ( new_dir ) current_dir = new_dir else : if S_ISLNK ( directory . st_mode ) : directory = self . resolve ( directory . contents ) current_dir = directory if directory . st_mode & S_IFDIR != S_IFDIR : self . raise_os_error ( errno . ENOTDIR , current_dir . path ) for new_dir in new_dirs : new_dir . st_mode = S_IFDIR | perm_bits self . _last_ino += 1 current_dir . st_ino = self . _last_ino return current_dir | Create directory_path and all the parent directories . |
14,637 | def create_file ( self , file_path , st_mode = S_IFREG | PERM_DEF_FILE , contents = '' , st_size = None , create_missing_dirs = True , apply_umask = False , encoding = None , errors = None , side_effect = None ) : return self . create_file_internally ( file_path , st_mode , contents , st_size , create_missing_dirs , apply_umask , encoding , errors , side_effect = side_effect ) | Create file_path including all the parent directories along the way . |
14,638 | def add_real_file ( self , source_path , read_only = True , target_path = None ) : target_path = target_path or source_path source_path = make_string_path ( source_path ) target_path = self . make_string_path ( target_path ) real_stat = os . stat ( source_path ) fake_file = self . create_file_internally ( target_path , read_from_real_fs = True ) fake_file . stat_result . set_from_stat_result ( real_stat ) if read_only : fake_file . st_mode &= 0o777444 fake_file . file_path = source_path self . change_disk_usage ( fake_file . size , fake_file . name , fake_file . st_dev ) return fake_file | Create file_path including all the parent directories along the way for an existing real file . The contents of the real file are read only on demand . |
14,639 | def add_real_directory ( self , source_path , read_only = True , lazy_read = True , target_path = None ) : source_path = self . _path_without_trailing_separators ( source_path ) if not os . path . exists ( source_path ) : self . raise_io_error ( errno . ENOENT , source_path ) target_path = target_path or source_path if lazy_read : parent_path = os . path . split ( target_path ) [ 0 ] if self . exists ( parent_path ) : parent_dir = self . get_object ( parent_path ) else : parent_dir = self . create_dir ( parent_path ) new_dir = FakeDirectoryFromRealDirectory ( source_path , self , read_only , target_path ) parent_dir . add_entry ( new_dir ) self . _last_ino += 1 new_dir . st_ino = self . _last_ino else : new_dir = self . create_dir ( target_path ) for base , _ , files in os . walk ( source_path ) : new_base = os . path . join ( new_dir . path , os . path . relpath ( base , source_path ) ) for fileEntry in files : self . add_real_file ( os . path . join ( base , fileEntry ) , read_only , os . path . join ( new_base , fileEntry ) ) return new_dir | Create a fake directory corresponding to the real directory at the specified path . Add entries in the fake directory corresponding to the entries in the real directory . |
14,640 | def create_file_internally ( self , file_path , st_mode = S_IFREG | PERM_DEF_FILE , contents = '' , st_size = None , create_missing_dirs = True , apply_umask = False , encoding = None , errors = None , read_from_real_fs = False , raw_io = False , side_effect = None ) : error_fct = self . raise_os_error if raw_io else self . raise_io_error file_path = self . make_string_path ( file_path ) file_path = self . absnormpath ( file_path ) if not is_int_type ( st_mode ) : raise TypeError ( 'st_mode must be of int type - did you mean to set contents?' ) if self . exists ( file_path , check_link = True ) : self . raise_os_error ( errno . EEXIST , file_path ) parent_directory , new_file = self . splitpath ( file_path ) if not parent_directory : parent_directory = self . cwd self . _auto_mount_drive_if_needed ( parent_directory ) if not self . exists ( parent_directory ) : if not create_missing_dirs : error_fct ( errno . ENOENT , parent_directory ) self . create_dir ( parent_directory ) else : parent_directory = self . _original_path ( parent_directory ) if apply_umask : st_mode &= ~ self . umask if read_from_real_fs : file_object = FakeFileFromRealFile ( file_path , filesystem = self , side_effect = side_effect ) else : file_object = FakeFile ( new_file , st_mode , filesystem = self , encoding = encoding , errors = errors , side_effect = side_effect ) self . _last_ino += 1 file_object . st_ino = self . _last_ino self . add_object ( parent_directory , file_object , error_fct ) if st_size is None and contents is None : contents = '' if ( not read_from_real_fs and ( contents is not None or st_size is not None ) ) : try : if st_size is not None : file_object . set_large_file_size ( st_size ) else : file_object . _set_initial_contents ( contents ) except IOError : self . remove_object ( file_path ) raise return file_object | Internal fake file creator that supports both normal fake files and fake files based on real files . |
14,641 | def create_symlink ( self , file_path , link_target , create_missing_dirs = True ) : if not self . _is_link_supported ( ) : raise OSError ( "Symbolic links are not supported " "on Windows before Python 3.2" ) file_path = self . make_string_path ( file_path ) link_target = self . make_string_path ( link_target ) file_path = self . normcase ( file_path ) if self . ends_with_path_separator ( file_path ) : if self . exists ( file_path ) : self . raise_os_error ( errno . EEXIST , file_path ) if self . exists ( link_target ) : if not self . is_windows_fs : self . raise_os_error ( errno . ENOENT , file_path ) else : if self . is_windows_fs : self . raise_os_error ( errno . EINVAL , link_target ) if not self . exists ( self . _path_without_trailing_separators ( file_path ) , check_link = True ) : self . raise_os_error ( errno . ENOENT , link_target ) if self . is_macos : if self . exists ( file_path , check_link = True ) : self . remove_object ( file_path ) else : self . raise_os_error ( errno . EEXIST , link_target ) if not self . islink ( file_path ) : file_path = self . resolve_path ( file_path ) link_target = make_string_path ( link_target ) return self . create_file_internally ( file_path , st_mode = S_IFLNK | PERM_DEF , contents = link_target , create_missing_dirs = create_missing_dirs , raw_io = True ) | Create the specified symlink pointed at the specified link target . |
14,642 | def makedirs ( self , dir_name , mode = PERM_DEF , exist_ok = False ) : ends_with_sep = self . ends_with_path_separator ( dir_name ) dir_name = self . absnormpath ( dir_name ) if ( ends_with_sep and self . is_macos and self . exists ( dir_name , check_link = True ) and not self . exists ( dir_name ) ) : self . remove_object ( dir_name ) path_components = self . _path_components ( dir_name ) current_dir = self . root for component in path_components : if ( component not in current_dir . contents or not isinstance ( current_dir . contents , dict ) ) : break else : current_dir = current_dir . contents [ component ] try : self . create_dir ( dir_name , mode & ~ self . umask ) except ( IOError , OSError ) as e : if ( not exist_ok or not isinstance ( self . resolve ( dir_name ) , FakeDirectory ) ) : if self . is_windows_fs and e . errno == errno . ENOTDIR : e . errno = errno . ENOENT self . raise_os_error ( e . errno , e . filename ) | Create a leaf Fake directory and create any non - existent parent dirs . |
14,643 | def isdir ( self , path , follow_symlinks = True ) : return self . _is_of_type ( path , S_IFDIR , follow_symlinks ) | Determine if path identifies a directory . |
14,644 | def isfile ( self , path , follow_symlinks = True ) : return self . _is_of_type ( path , S_IFREG , follow_symlinks ) | Determine if path identifies a regular file . |
14,645 | def confirmdir ( self , target_directory ) : try : directory = self . resolve ( target_directory ) except IOError as exc : self . raise_os_error ( exc . errno , target_directory ) if not directory . st_mode & S_IFDIR : if self . is_windows_fs and IS_PY2 : error_nr = errno . EINVAL else : error_nr = errno . ENOTDIR self . raise_os_error ( error_nr , target_directory , 267 ) return directory | Test that the target is actually a directory raising OSError if not . |
14,646 | def listdir ( self , target_directory ) : target_directory = self . resolve_path ( target_directory , allow_fd = True ) directory = self . confirmdir ( target_directory ) directory_contents = directory . contents return list ( directory_contents . keys ( ) ) | Return a list of file names in target_directory . |
14,647 | def getsize ( self , path ) : try : file_obj = self . filesystem . resolve ( path ) if ( self . filesystem . ends_with_path_separator ( path ) and S_IFMT ( file_obj . st_mode ) != S_IFDIR ) : error_nr = ( errno . EINVAL if self . filesystem . is_windows_fs else errno . ENOTDIR ) self . filesystem . raise_os_error ( error_nr , path ) return file_obj . st_size except IOError as exc : raise os . error ( exc . errno , exc . strerror ) | Return the file object size in bytes . |
14,648 | def isabs ( self , path ) : if self . filesystem . is_windows_fs : path = self . splitdrive ( path ) [ 1 ] path = make_string_path ( path ) sep = self . filesystem . _path_separator ( path ) altsep = self . filesystem . _alternative_path_separator ( path ) if self . filesystem . is_windows_fs : return len ( path ) > 0 and path [ : 1 ] in ( sep , altsep ) else : return ( path . startswith ( sep ) or altsep is not None and path . startswith ( altsep ) ) | Return True if path is an absolute pathname . |
14,649 | def getmtime ( self , path ) : try : file_obj = self . filesystem . resolve ( path ) return file_obj . st_mtime except IOError : self . filesystem . raise_os_error ( errno . ENOENT , winerror = 3 ) | Returns the modification time of the fake file . |
14,650 | def getatime ( self , path ) : try : file_obj = self . filesystem . resolve ( path ) except IOError : self . filesystem . raise_os_error ( errno . ENOENT ) return file_obj . st_atime | Returns the last access time of the fake file . |
14,651 | def getctime ( self , path ) : try : file_obj = self . filesystem . resolve ( path ) except IOError : self . filesystem . raise_os_error ( errno . ENOENT ) return file_obj . st_ctime | Returns the creation time of the fake file . |
14,652 | def abspath ( self , path ) : def getcwd ( ) : if IS_PY2 and isinstance ( path , text_type ) : return self . os . getcwdu ( ) elif not IS_PY2 and isinstance ( path , bytes ) : return self . os . getcwdb ( ) else : return self . os . getcwd ( ) path = make_string_path ( path ) sep = self . filesystem . _path_separator ( path ) altsep = self . filesystem . _alternative_path_separator ( path ) if not self . isabs ( path ) : path = self . join ( getcwd ( ) , path ) elif ( self . filesystem . is_windows_fs and path . startswith ( sep ) or altsep is not None and path . startswith ( altsep ) ) : cwd = getcwd ( ) if self . filesystem . _starts_with_drive_letter ( cwd ) : path = self . join ( cwd [ : 2 ] , path ) return self . normpath ( path ) | Return the absolute version of a path . |
14,653 | def normcase ( self , path ) : path = self . filesystem . normcase ( path ) if self . filesystem . is_windows_fs : path = path . lower ( ) return path | Convert to lower case under windows replaces additional path separator . |
14,654 | def relpath ( self , path , start = None ) : if not path : raise ValueError ( "no path specified" ) path = make_string_path ( path ) if start is not None : start = make_string_path ( start ) else : start = self . filesystem . cwd if self . filesystem . alternative_path_separator is not None : path = path . replace ( self . filesystem . alternative_path_separator , self . _os_path . sep ) start = start . replace ( self . filesystem . alternative_path_separator , self . _os_path . sep ) path = path . replace ( self . filesystem . path_separator , self . _os_path . sep ) start = start . replace ( self . filesystem . path_separator , self . _os_path . sep ) path = self . _os_path . relpath ( path , start ) return path . replace ( self . _os_path . sep , self . filesystem . path_separator ) | We mostly rely on the native implementation and adapt the path separator . |
14,655 | def realpath ( self , filename ) : if self . filesystem . is_windows_fs : return self . abspath ( filename ) filename = make_string_path ( filename ) path , ok = self . _joinrealpath ( filename [ : 0 ] , filename , { } ) return self . abspath ( path ) | Return the canonical path of the specified filename eliminating any symbolic links encountered in the path . |
14,656 | def _joinrealpath ( self , path , rest , seen ) : curdir = self . filesystem . _matching_string ( path , '.' ) pardir = self . filesystem . _matching_string ( path , '..' ) sep = self . filesystem . _path_separator ( path ) if self . isabs ( rest ) : rest = rest [ 1 : ] path = sep while rest : name , _ , rest = rest . partition ( sep ) if not name or name == curdir : continue if name == pardir : if path : path , name = self . filesystem . splitpath ( path ) if name == pardir : path = self . filesystem . joinpaths ( path , pardir , pardir ) else : path = pardir continue newpath = self . filesystem . joinpaths ( path , name ) if not self . filesystem . islink ( newpath ) : path = newpath continue if newpath in seen : path = seen [ newpath ] if path is not None : continue return self . filesystem . joinpaths ( newpath , rest ) , False seen [ newpath ] = None path , ok = self . _joinrealpath ( path , self . filesystem . readlink ( newpath ) , seen ) if not ok : return self . filesystem . joinpaths ( path , rest ) , False seen [ newpath ] = path return path , True | Join two paths normalizing and eliminating any symbolic links encountered in the second path . Taken from Python source and adapted . |
14,657 | def ismount ( self , path ) : path = make_string_path ( path ) if not path : return False normed_path = self . filesystem . absnormpath ( path ) sep = self . filesystem . _path_separator ( path ) if self . filesystem . is_windows_fs : if self . filesystem . alternative_path_separator is not None : path_seps = ( sep , self . filesystem . _alternative_path_separator ( path ) ) else : path_seps = ( sep , ) drive , rest = self . filesystem . splitdrive ( normed_path ) if drive and drive [ : 1 ] in path_seps : return ( not rest ) or ( rest in path_seps ) if rest in path_seps : return True for mount_point in self . filesystem . mount_points : if normed_path . rstrip ( sep ) == mount_point . rstrip ( sep ) : return True return False | Return true if the given path is a mount point . |
14,658 | def _fdopen_ver2 ( self , file_des , mode = 'r' , bufsize = None ) : if not is_int_type ( file_des ) : raise TypeError ( 'an integer is required' ) try : return FakeFileOpen ( self . filesystem ) . call ( file_des , mode = mode ) except IOError as exc : self . filesystem . raise_os_error ( exc . errno , exc . filename ) | Returns an open file object connected to the file descriptor file_des . |
14,659 | def _umask ( self ) : if self . filesystem . is_windows_fs : return 0 if sys . platform == 'win32' : return 0o002 else : mask = os . umask ( 0 ) os . umask ( mask ) return mask | Return the current umask . |
14,660 | def open ( self , file_path , flags , mode = None , dir_fd = None ) : file_path = self . _path_with_dir_fd ( file_path , self . open , dir_fd ) if mode is None : if self . filesystem . is_windows_fs : mode = 0o666 else : mode = 0o777 & ~ self . _umask ( ) open_modes = _OpenModes ( must_exist = not flags & os . O_CREAT , can_read = not flags & os . O_WRONLY , can_write = flags & ( os . O_RDWR | os . O_WRONLY ) , truncate = flags & os . O_TRUNC , append = flags & os . O_APPEND , must_not_exist = flags & os . O_EXCL ) if open_modes . must_not_exist and open_modes . must_exist : raise NotImplementedError ( 'O_EXCL without O_CREAT mode is not supported' ) if ( not self . filesystem . is_windows_fs and self . filesystem . exists ( file_path ) ) : obj = self . filesystem . resolve ( file_path ) if isinstance ( obj , FakeDirectory ) : if ( ( not open_modes . must_exist and not self . filesystem . is_macos ) or open_modes . can_write ) : self . filesystem . raise_os_error ( errno . EISDIR , file_path ) dir_wrapper = FakeDirWrapper ( obj , file_path , self . filesystem ) file_des = self . filesystem . _add_open_file ( dir_wrapper ) dir_wrapper . filedes = file_des return file_des str_flags = 'b' delete_on_close = False if hasattr ( os , 'O_TEMPORARY' ) : delete_on_close = flags & os . O_TEMPORARY == os . O_TEMPORARY fake_file = FakeFileOpen ( self . filesystem , delete_on_close = delete_on_close , raw_io = True ) ( file_path , str_flags , open_modes = open_modes ) if fake_file . file_object != self . filesystem . dev_null : self . chmod ( file_path , mode ) return fake_file . fileno ( ) | Return the file descriptor for a FakeFile . |
14,661 | def close ( self , file_des ) : file_handle = self . filesystem . get_open_file ( file_des ) file_handle . close ( ) | Close a file descriptor . |
14,662 | def read ( self , file_des , num_bytes ) : file_handle = self . filesystem . get_open_file ( file_des ) file_handle . raw_io = True return file_handle . read ( num_bytes ) | Read number of bytes from a file descriptor returns bytes read . |
14,663 | def write ( self , file_des , contents ) : file_handle = self . filesystem . get_open_file ( file_des ) if isinstance ( file_handle , FakeDirWrapper ) : self . filesystem . raise_os_error ( errno . EBADF , file_handle . file_path ) if isinstance ( file_handle , FakePipeWrapper ) : return file_handle . write ( contents ) file_handle . raw_io = True file_handle . _sync_io ( ) file_handle . update_flush_pos ( ) file_handle . write ( contents ) file_handle . flush ( ) return len ( contents ) | Write string to file descriptor returns number of bytes written . |
14,664 | def fstat ( self , file_des ) : file_object = self . filesystem . get_open_file ( file_des ) . get_object ( ) return file_object . stat_result . copy ( ) | Return the os . stat - like tuple for the FakeFile object of file_des . |
14,665 | def umask ( self , new_mask ) : if not is_int_type ( new_mask ) : raise TypeError ( 'an integer is required' ) old_umask = self . filesystem . umask self . filesystem . umask = new_mask return old_umask | Change the current umask . |
14,666 | def chdir ( self , target_directory ) : target_directory = self . filesystem . resolve_path ( target_directory , allow_fd = True ) self . filesystem . confirmdir ( target_directory ) directory = self . filesystem . resolve ( target_directory ) if not is_root ( ) and not directory . st_mode | PERM_EXE : self . filesystem . raise_os_error ( errno . EACCES , directory ) self . filesystem . cwd = target_directory | Change current working directory to target directory . |
14,667 | def lstat ( self , entry_path , dir_fd = None ) : entry_path = self . _path_with_dir_fd ( entry_path , self . lstat , dir_fd ) return self . filesystem . stat ( entry_path , follow_symlinks = False ) | Return the os . stat - like tuple for entry_path not following symlinks . |
14,668 | def removedirs ( self , target_directory ) : target_directory = self . filesystem . absnormpath ( target_directory ) directory = self . filesystem . confirmdir ( target_directory ) if directory . contents : self . filesystem . raise_os_error ( errno . ENOTEMPTY , self . path . basename ( target_directory ) ) else : self . rmdir ( target_directory ) head , tail = self . path . split ( target_directory ) if not tail : head , tail = self . path . split ( head ) while head and tail : head_dir = self . filesystem . confirmdir ( head ) if head_dir . contents : break self . filesystem . rmdir ( head , allow_symlink = True ) head , tail = self . path . split ( head ) | Remove a leaf fake directory and all empty intermediate ones . |
14,669 | def makedirs ( self , dir_name , mode = PERM_DEF , exist_ok = None ) : if exist_ok is None : exist_ok = False elif sys . version_info < ( 3 , 2 ) : raise TypeError ( "makedir() got an unexpected " "keyword argument 'exist_ok'" ) self . filesystem . makedirs ( dir_name , mode , exist_ok ) | Create a leaf Fake directory + create any non - existent parent dirs . |
14,670 | def _path_with_dir_fd ( self , path , fct , dir_fd ) : if dir_fd is not None : if sys . version_info < ( 3 , 3 ) : raise TypeError ( "%s() got an unexpected keyword " "argument 'dir_fd'" % fct . __name__ ) real_fct = getattr ( os , fct . __name__ ) if real_fct not in self . supports_dir_fd : raise NotImplementedError ( 'dir_fd unavailable on this platform' ) if isinstance ( path , int ) : raise ValueError ( "%s: Can't specify dir_fd without " "matching path" % fct . __name__ ) if not self . path . isabs ( path ) : return self . path . join ( self . filesystem . get_open_file ( dir_fd ) . get_object ( ) . path , path ) return path | Return the path considering dir_fd . Raise on nmvalid parameters . |
14,671 | def access ( self , path , mode , dir_fd = None , follow_symlinks = None ) : if follow_symlinks is not None and sys . version_info < ( 3 , 3 ) : raise TypeError ( "access() got an unexpected " "keyword argument 'follow_symlinks'" ) path = self . _path_with_dir_fd ( path , self . access , dir_fd ) try : stat_result = self . stat ( path , follow_symlinks = follow_symlinks ) except OSError as os_error : if os_error . errno == errno . ENOENT : return False raise if is_root ( ) : mode &= ~ os . W_OK return ( mode & ( ( stat_result . st_mode >> 6 ) & 7 ) ) == mode | Check if a file exists and has the specified permissions . |
14,672 | def lchmod ( self , path , mode ) : if self . filesystem . is_windows_fs : raise ( NameError , "name 'lchmod' is not defined" ) self . filesystem . chmod ( path , mode , follow_symlinks = False ) | Change the permissions of a file as encoded in integer mode . If the file is a link the permissions of the link are changed . |
14,673 | def chown ( self , path , uid , gid , dir_fd = None , follow_symlinks = None ) : if follow_symlinks is None : follow_symlinks = True elif sys . version_info < ( 3 , 3 ) : raise TypeError ( "chown() got an unexpected keyword argument 'follow_symlinks'" ) path = self . _path_with_dir_fd ( path , self . chown , dir_fd ) try : file_object = self . filesystem . resolve ( path , follow_symlinks , allow_fd = True ) except IOError as io_error : if io_error . errno == errno . ENOENT : self . filesystem . raise_os_error ( errno . ENOENT , path ) raise if not ( ( is_int_type ( uid ) or uid is None ) and ( is_int_type ( gid ) or gid is None ) ) : raise TypeError ( "An integer is required" ) if uid != - 1 : file_object . st_uid = uid if gid != - 1 : file_object . st_gid = gid | Set ownership of a faked file . |
14,674 | def mknod ( self , filename , mode = None , device = None , dir_fd = None ) : if self . filesystem . is_windows_fs : raise ( AttributeError , "module 'os' has no attribute 'mknode'" ) if mode is None : mode = S_IFREG | 0o600 if device or not mode & S_IFREG and not is_root ( ) : self . filesystem . raise_os_error ( errno . EPERM ) filename = self . _path_with_dir_fd ( filename , self . mknod , dir_fd ) head , tail = self . path . split ( filename ) if not tail : if self . filesystem . exists ( head , check_link = True ) : self . filesystem . raise_os_error ( errno . EEXIST , filename ) self . filesystem . raise_os_error ( errno . ENOENT , filename ) if tail in ( b'.' , u'.' , b'..' , u'..' ) : self . filesystem . raise_os_error ( errno . ENOENT , filename ) if self . filesystem . exists ( filename , check_link = True ) : self . filesystem . raise_os_error ( errno . EEXIST , filename ) try : self . filesystem . add_object ( head , FakeFile ( tail , mode & ~ self . filesystem . umask , filesystem = self . filesystem ) ) except IOError as e : self . filesystem . raise_os_error ( e . errno , filename ) | Create a filesystem node named filename . |
14,675 | def symlink ( self , link_target , path , dir_fd = None ) : link_target = self . _path_with_dir_fd ( link_target , self . symlink , dir_fd ) self . filesystem . create_symlink ( path , link_target , create_missing_dirs = False ) | Creates the specified symlink pointed at the specified link target . |
14,676 | def flush ( self ) : self . _check_open_file ( ) if self . allow_update and not self . is_stream : contents = self . _io . getvalue ( ) if self . _append : self . _sync_io ( ) old_contents = ( self . file_object . byte_contents if is_byte_string ( contents ) else self . file_object . contents ) contents = old_contents + contents [ self . _flush_pos : ] self . _set_stream_contents ( contents ) self . update_flush_pos ( ) else : self . _io . flush ( ) if self . file_object . set_contents ( contents , self . _encoding ) : if self . _filesystem . is_windows_fs : self . _changed = True else : current_time = time . time ( ) self . file_object . st_ctime = current_time self . file_object . st_mtime = current_time self . _file_epoch = self . file_object . epoch if not self . is_stream : self . _flush_related_files ( ) | Flush file contents to disk . |
14,677 | def tell ( self ) : self . _check_open_file ( ) if self . _flushes_after_tell ( ) : self . flush ( ) if not self . _append : return self . _io . tell ( ) if self . _read_whence : write_seek = self . _io . tell ( ) self . _io . seek ( self . _read_seek , self . _read_whence ) self . _read_seek = self . _io . tell ( ) self . _read_whence = 0 self . _io . seek ( write_seek ) return self . _read_seek | Return the file s current position . |
14,678 | def _sync_io ( self ) : if self . _file_epoch == self . file_object . epoch : return if self . _io . binary : contents = self . file_object . byte_contents else : contents = self . file_object . contents self . _set_stream_contents ( contents ) self . _file_epoch = self . file_object . epoch | Update the stream with changes to the file object contents . |
14,679 | def _read_wrappers ( self , name ) : io_attr = getattr ( self . _io , name ) def read_wrapper ( * args , ** kwargs ) : self . _io . seek ( self . _read_seek , self . _read_whence ) ret_value = io_attr ( * args , ** kwargs ) self . _read_seek = self . _io . tell ( ) self . _read_whence = 0 self . _io . seek ( 0 , 2 ) return ret_value return read_wrapper | Wrap a stream attribute in a read wrapper . |
14,680 | def _other_wrapper ( self , name , writing ) : io_attr = getattr ( self . _io , name ) def other_wrapper ( * args , ** kwargs ) : write_seek = self . _io . tell ( ) ret_value = io_attr ( * args , ** kwargs ) if write_seek != self . _io . tell ( ) : self . _read_seek = self . _io . tell ( ) self . _read_whence = 0 if not writing or not IS_PY2 : return ret_value return other_wrapper | Wrap a stream attribute in an other_wrapper . |
14,681 | def close ( self ) : self . _filesystem . open_files [ self . filedes ] . remove ( self ) os . close ( self . fd ) | Close the pipe descriptor . |
14,682 | def call ( self , file_ , mode = 'r' , buffering = - 1 , encoding = None , errors = None , newline = None , closefd = True , opener = None , open_modes = None ) : binary = 'b' in mode newline , open_modes = self . _handle_file_mode ( mode , newline , open_modes ) file_object , file_path , filedes , real_path = self . _handle_file_arg ( file_ ) if not filedes : closefd = True error_fct = ( self . filesystem . raise_os_error if self . raw_io else self . filesystem . raise_io_error ) if ( open_modes . must_not_exist and ( file_object or self . filesystem . islink ( file_path ) and not self . filesystem . is_windows_fs ) ) : error_fct ( errno . EEXIST , file_path ) if file_object : if ( not is_root ( ) and ( ( open_modes . can_read and not file_object . st_mode & PERM_READ ) or ( open_modes . can_write and not file_object . st_mode & PERM_WRITE ) ) ) : error_fct ( errno . EACCES , file_path ) if open_modes . can_write : if open_modes . truncate : file_object . set_contents ( '' ) else : if open_modes . must_exist : error_fct ( errno . ENOENT , file_path ) if self . filesystem . islink ( file_path ) : link_object = self . filesystem . resolve ( file_path , follow_symlinks = False ) target_path = link_object . contents else : target_path = file_path if self . filesystem . ends_with_path_separator ( target_path ) : error = ( errno . EINVAL if self . filesystem . is_windows_fs else errno . ENOENT if self . filesystem . is_macos else errno . EISDIR ) error_fct ( error , file_path ) file_object = self . filesystem . create_file_internally ( real_path , create_missing_dirs = False , apply_umask = True , raw_io = self . raw_io ) if S_ISDIR ( file_object . st_mode ) : if self . filesystem . is_windows_fs : error_fct ( errno . EACCES , file_path ) else : error_fct ( errno . EISDIR , file_path ) file_object . opened_as = file_path if open_modes . truncate : current_time = time . time ( ) file_object . st_mtime = current_time if not self . filesystem . is_windows_fs : file_object . st_ctime = current_time fakefile = FakeFileWrapper ( file_object , file_path , update = open_modes . can_write , read = open_modes . can_read , append = open_modes . append , delete_on_close = self . _delete_on_close , filesystem = self . filesystem , newline = newline , binary = binary , closefd = closefd , encoding = encoding , errors = errors , raw_io = self . raw_io , use_io = self . _use_io ) if filedes is not None : fakefile . filedes = filedes self . filesystem . open_files [ filedes ] . append ( fakefile ) else : fakefile . filedes = self . filesystem . _add_open_file ( fakefile ) return fakefile | Return a file - like object with the contents of the target file object . |
14,683 | def is_int_type ( val ) : try : return isinstance ( val , ( int , long ) ) except NameError : return isinstance ( val , int ) | Return True if val is of integer type . |
14,684 | def copy ( self ) : stat_result = copy ( self ) stat_result . use_float = self . use_float return stat_result | Return a copy where the float usage is hard - coded to mimic the behavior of the real os . stat_result . |
14,685 | def stat_float_times ( cls , newvalue = None ) : if newvalue is not None : cls . _stat_float_times = bool ( newvalue ) return cls . _stat_float_times | Determine whether a file s time stamps are reported as floats or ints . |
14,686 | def st_ctime ( self ) : ctime = self . _st_ctime_ns / 1e9 return ctime if self . use_float else int ( ctime ) | Return the creation time in seconds . |
14,687 | def st_atime ( self ) : atime = self . _st_atime_ns / 1e9 return atime if self . use_float else int ( atime ) | Return the access time in seconds . |
14,688 | def st_mtime ( self ) : mtime = self . _st_mtime_ns / 1e9 return mtime if self . use_float else int ( mtime ) | Return the modification time in seconds . |
14,689 | def detect_id_type ( sid ) : sid = str ( sid ) if not sid . isnumeric ( ) : if sid . startswith ( '2-s2.0-' ) : id_type = 'eid' elif '/' in sid : id_type = 'doi' elif 16 <= len ( sid ) <= 17 : id_type = 'pii' elif sid . isnumeric ( ) : if len ( sid ) < 10 : id_type = 'pubmed_id' else : id_type = 'scopus_id' else : raise ValueError ( 'ID type detection failed for \'{}\'.' . format ( sid ) ) return id_type | Method that tries to infer the type of abstract ID . |
14,690 | def download ( url , params = None , accept = "xml" , ** kwds ) : accepted = ( "json" , "xml" , "atom+xml" ) if accept . lower ( ) not in accepted : raise ValueError ( 'accept parameter must be one of ' + ', ' . join ( accepted ) ) key = config . get ( 'Authentication' , 'APIKey' ) header = { 'X-ELS-APIKey' : key } if config . has_option ( 'Authentication' , 'InstToken' ) : token = config . get ( 'Authentication' , 'InstToken' ) header . update ( { 'X-ELS-APIKey' : key , 'X-ELS-Insttoken' : token } ) header . update ( { 'Accept' : 'application/{}' . format ( accept ) } ) params . update ( ** kwds ) resp = requests . get ( url , headers = header , params = params ) try : reason = resp . reason . upper ( ) + " for url: " + url raise errors [ resp . status_code ] ( reason ) except KeyError : resp . raise_for_status ( ) return resp | Helper function to download a file and return its content . |
14,691 | def name_variants ( self ) : out = [ ] variant = namedtuple ( 'Variant' , 'name doc_count' ) for var in chained_get ( self . _json , [ 'name-variants' , 'name-variant' ] , [ ] ) : new = variant ( name = var [ '$' ] , doc_count = var . get ( '@doc-count' ) ) out . append ( new ) return out | A list of namedtuples representing variants of the affiliation name with number of documents referring to this variant . |
14,692 | def url ( self ) : url = self . xml . find ( 'coredata/link[@rel="scopus-affiliation"]' ) if url is not None : url = url . get ( 'href' ) return url | URL to the affiliation s profile page . |
14,693 | def parse_date_created ( dct ) : date = dct [ 'date-created' ] if date : return ( int ( date [ '@year' ] ) , int ( date [ '@month' ] ) , int ( date [ '@day' ] ) ) else : return ( None , None , None ) | Helper function to parse date - created from profile . |
14,694 | def affiliation_history ( self ) : affs = self . _json . get ( 'affiliation-history' , { } ) . get ( 'affiliation' ) try : return [ d [ '@id' ] for d in affs ] except TypeError : return None | Unordered list of IDs of all affiliations the author was affiliated with acccording to Scopus . |
14,695 | def historical_identifier ( self ) : hist = chained_get ( self . _json , [ "coredata" , 'historical-identifier' ] , [ ] ) return [ d [ '$' ] . split ( ":" ) [ - 1 ] for d in hist ] or None | Scopus IDs of previous profiles now compromising this profile . |
14,696 | def identifier ( self ) : ident = self . _json [ 'coredata' ] [ 'dc:identifier' ] . split ( ":" ) [ - 1 ] if ident != self . _id : text = "Profile with ID {} has been merged and the new ID is " "{}. Please update your records manually. Files have " "been cached with the old ID." . format ( self . _id , ident ) warn ( text , UserWarning ) return ident | The author s ID . Might differ from the one provided . |
14,697 | def name_variants ( self ) : fields = 'indexed_name initials surname given_name doc_count' variant = namedtuple ( 'Variant' , fields ) path = [ 'author-profile' , 'name-variant' ] out = [ variant ( indexed_name = var [ 'indexed-name' ] , surname = var [ 'surname' ] , doc_count = var . get ( '@doc-count' ) , initials = var [ 'initials' ] , given_name = var . get ( 'given-name' ) ) for var in listify ( chained_get ( self . _json , path , [ ] ) ) ] return out or None | List of named tuples containing variants of the author name with number of documents published with that variant . |
14,698 | def publication_range ( self ) : r = self . _json [ 'author-profile' ] [ 'publication-range' ] return ( r [ '@start' ] , r [ '@end' ] ) return self . _json [ 'coredata' ] . get ( 'orcid' ) | Tuple containing years of first and last publication . |
14,699 | def get_documents ( self , subtypes = None , refresh = False ) : search = ScopusSearch ( 'au-id({})' . format ( self . identifier ) , refresh ) if subtypes : return [ p for p in search . results if p . subtype in subtypes ] else : return search . results | Return list of author s publications using ScopusSearch which fit a specified set of document subtypes . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.