• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utils.safe_eval函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中numpy.lib.utils.safe_eval函数的典型用法代码示例。如果您正苦于以下问题:Python safe_eval函数的具体用法?Python safe_eval怎么用?Python safe_eval使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了safe_eval函数的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: save

def save(file, iarray, metafile=None, version=(1, 0)):
    """Save a info array to a .npy file and a metadata file.

    Similar to the numpy.save function.

    Parameters
    ----------
    file: file handle or str
        File or file name to write the array to in .npy format.
    iarray: InfoArray object or array with similar interface
        Array to be written to file with meta data.
    metafile: str
        File name for the meta data.  The `info` attribute of `iarray` will be
        written here. Default is None, where the it is
        assumed to be the file name associated with `file` with ".meta"
        appended.
    """

    # Restrict to version (1,0) because we've only written write_header for
    # this version.
    if version != (1, 0):
        raise ValueError("Only version (1,0) is safe from this function.")

    # Make sure that the meta data will be representable as a string.
    infostring = repr(iarray.info)
    try:
        safe_eval(infostring)
    except SyntaxError:
        raise ValueError

    # Save the array in .npy format.
    if isinstance(file, basestring):
        fid = open(file, "wb")
    else:
        fid = file

    npfor.write_array(fid, iarray, version=version)

    # Figure out what the filename for the meta data should be.
    if metafile is None:
        try:
            fname = file.name
        except AttributeError:
            fname = file
        metafile = fname + ".meta"

    # Save the meta data.
    info_fid = open(metafile, 'w')
    try:
        info_fid.write(infostring)
    finally:
        info_fid.close()
开发者ID:eric-switzer,项目名称:algebra_base,代码行数:52,代码来源:file_io.py


示例2: load_h5

def load_h5(h5obj, path):
    """Load an info array from an hdf5 file.

    Parameters
    ----------
    h5obj: h5py File or Group object
        File from which the info array will be read from.
    path: string
        Path within `h5obj` to read the array.

    Returns
    -------
    iarray: InfoArray
        Array loaded from file.
    """

    # TODO:  Allow `h5obj` to be a string with a path to a file to be opened
    # and then closed.
    data = h5obj[path]
    iarray = np.empty(data.shape, data.dtype)
    iarray[:] = data[:]
    info = {}

    for key, value in data.attrs.iteritems():
        info[key] = safe_eval(value)

    iarray = InfoArray(iarray, info)

    return iarray
开发者ID:eric-switzer,项目名称:algebra_base,代码行数:29,代码来源:file_io.py


示例3: open_memmap

def open_memmap(filename, mode='r+', dtype=None, shape=None,
                fortran_order=False, version=(1, 0), metafile=None):
    """Open a file and memory map it to an InfoMemmap object.

    This is similar to the numpy.lib.format.openmemmap() function but also
    deals with the meta data dictionary, which is read and written from a
    meta data file.

    The only extra argument over the numpy version is the meta data file name
    `metafile`.

    Parameters
    ----------
    metafile: str
        File name for which the `info` attribute of the returned InfoMemmap
        will be read from and written to. Default is None, where the it is
        assumed to be `filename` + ".meta".

    Returns
    -------
    marray: InfoMemmap
        The `info` is intialized as an empty dictionary if `mode` is 'w' or if
        the file corresponding to `metafile` does not exist.  The `metafile`
        attribute of marray is set to the `metafile` parameter unless `mode` is
        'r' or 'c' in which case it is set to None.
    """

    # Restrict to version (1,0) because we've only written write_header for
    # this version.
    if version != (1, 0):
        raise ValueError("Only version (1,0) is safe from this function.")

    # Memory map the data part.
    marray = npfor.open_memmap(filename, mode, dtype, shape, fortran_order,
                               version)

    # Get the file name for the meta data.
    if metafile is None:
        metafile = filename + '.meta'

    # Read the meta data if need be.
    if ('r' in mode or mode is 'c') and os.path.isfile(metafile):
        info_fid = open(metafile, 'r')
        try:
            infostring = info_fid.readline()
        finally:
            info_fid.close()
        info = safe_eval(infostring)
    else:
        info = {}

    # In read mode don't pass a metafile to protect the meta data.
    if mode is 'r' or mode is 'c':
        metafile = None

    marray = info_header.InfoMemmap(marray, info, metafile)

    return marray
开发者ID:eric-switzer,项目名称:algebra_base,代码行数:58,代码来源:file_io.py


示例4: read_localarray_header

def read_localarray_header(fp, version):
    """
    Read an array header from a filelike object using the 1.0 file format
    version.

    This will leave the file object located just after the header.

    Parameters
    ----------
    fp : filelike object
        A file object or something with a `.read()` method like a file.
    version : tuple of int

    Returns
    -------
    __version__ : str
        Version of the Distributed Array Protocol used.
    dim_data : tuple
        A tuple containing a dictionary for each dimension of the underlying
        array, as described in the Distributed Array Protocol.

    Raises
    ------
    ValueError
        If the data is invalid.

    """
    # Read an unsigned, little-endian short int which has the length of the
    # header.
    import struct

    if version == (1, 0):
        hlength_str = _read_bytes(fp, 2, "Array header length")
        header_length = struct.unpack("<H", hlength_str)[0]
        header = _read_bytes(fp, header_length, "Array header")
    else:
        raise ValueError("Invalid version %r" % version)

    # The header is a pretty-printed string representation of a literal Python
    # dictionary with trailing newlines padded to a 16-byte boundary. The keys
    # are strings.
    try:
        d = safe_eval(header)
    except SyntaxError as e:
        msg = "Cannot parse header: %r\nException: %r"
        raise ValueError(msg % (header, e))
    if not isinstance(d, dict):
        msg = "Header is not a dictionary: %r"
        raise ValueError(msg % d)
    keys = sorted(d.keys())
    if keys != ["__version__", "dim_data"]:
        msg = "Header does not contain the correct keys: %r"
        raise ValueError(msg % (keys,))

    # TODO: Sanity check with the DAP validator

    return d["__version__"], d["dim_data"]
开发者ID:jhugon,项目名称:distarray,代码行数:57,代码来源:format.py


示例5: _read_array_header

def _read_array_header(fp, version):
    """
    see read_array_header_1_0
    """
    # Read an unsigned, little-endian short int which has the length of the
    # header.
    import struct
    if version == (1, 0):
        hlength_type = '<H'
    elif version == (2, 0):
        hlength_type = '<I'
    else:
        raise ValueError("Invalid version %r" % version)

    hlength_str = _read_bytes(fp, struct.calcsize(hlength_type), "array header length")
    header_length = struct.unpack(hlength_type, hlength_str)[0]
    header = _read_bytes(fp, header_length, "array header")

    # The header is a pretty-printed string representation of a literal
    # Python dictionary with trailing newlines padded to a ARRAY_ALIGN byte
    # boundary. The keys are strings.
    #   "shape" : tuple of int
    #   "fortran_order" : bool
    #   "descr" : dtype.descr
    header = _filter_header(header)
    try:
        d = safe_eval(header)
    except SyntaxError as e:
        msg = "Cannot parse header: %r\nException: %r"
        raise ValueError(msg % (header, e))
    if not isinstance(d, dict):
        msg = "Header is not a dictionary: %r"
        raise ValueError(msg % d)
    keys = sorted(d.keys())
    if keys != ['descr', 'fortran_order', 'shape']:
        msg = "Header does not contain the correct keys: %r"
        raise ValueError(msg % (keys,))

    # Sanity-check the values.
    if (not isinstance(d['shape'], tuple) or
            not numpy.all([isinstance(x, (int, long)) for x in d['shape']])):
        msg = "shape is not valid: %r"
        raise ValueError(msg % (d['shape'],))
    if not isinstance(d['fortran_order'], bool):
        msg = "fortran_order is not a valid bool: %r"
        raise ValueError(msg % (d['fortran_order'],))
    try:
        dtype = descr_to_dtype(d['descr'])
    except TypeError as e:
        msg = "descr is not a valid dtype descriptor: %r"
        raise ValueError(msg % (d['descr'],))

    return d['shape'], d['fortran_order'], dtype
开发者ID:Horta,项目名称:numpy,代码行数:53,代码来源:format.py


示例6: _info_flush

    def _info_flush(self):
        """Write the info array to disk only."""
        # Prior to numpy 1.5, we can't get the mode, so just assume we are
        # allowed to write
        mode = getattr(self, "mode", "r+")
        if ("+" in mode or "w" in mode) and self.metafile is not None:
            # Convert info dictionary to a pretty string.
            infostring = repr(self.info)

            try:
                safe_eval(infostring)
            except SyntaxError:
                raise ce.DataError("Array info not representable as a string.")

            # Save the meta data.
            info_fid = open(self.metafile, "w")

            try:
                info_fid.write(infostring)
            finally:
                info_fid.close()
开发者ID:eric-switzer,项目名称:algebra_base,代码行数:21,代码来源:info_header.py


示例7: read_array_header_1_0

def read_array_header_1_0(fp):
    """
    Read an array header from a filelike object using the 1.0 file format
    version.

    This will leave the file object located just after the header.

    Parameters
    ----------
    fp : filelike object
        A file object or something with a `.read()` method like a file.

    Returns
    -------
    shape : tuple of int
        The shape of the array.
    fortran_order : bool
        The array data will be written out directly if it is either C-contiguous
        or Fortran-contiguous. Otherwise, it will be made contiguous before
        writing it out.
    dtype : dtype
        The dtype of the file's data.

    Raises
    ------
    ValueError :
        If the data is invalid.

    """
    # Read an unsigned, little-endian short int which has the length of the
    # header.
    import struct
    hlength_str = fp.read(2)
    if len(hlength_str) != 2:
        msg = "EOF at %s before reading array header length"
        raise ValueError(msg % fp.tell())
    header_length = struct.unpack('<H', hlength_str)[0]
    header = fp.read(header_length)
    if len(header) != header_length:
        raise ValueError("EOF at %s before reading array header" % fp.tell())

    # The header is a pretty-printed string representation of a literal Python
    # dictionary with trailing newlines padded to a 16-byte boundary. The keys
    # are strings.
    #   "shape" : tuple of int
    #   "fortran_order" : bool
    #   "descr" : dtype.descr
    try:
        d = safe_eval(header)
    except SyntaxError, e:
        msg = "Cannot parse header: %r\nException: %r"
        raise ValueError(msg % (header, e))
开发者ID:Ademan,项目名称:NumPy-GSoC,代码行数:52,代码来源:format.py


示例8: _dtype_unpack

 def _dtype_unpack(self, s):
     # pulled from np.lib.format.read_array_header_1_0
     # The header is a pretty-printed string representation of a literal Python
     # dictionary with trailing newlines padded to a 16-byte boundary. The keys
     # are strings.
     #   "shape" : tuple of int
     #   "fortran_order" : bool
     #   "descr" : dtype.descr
     try:
         d = safe_eval(s)
     except SyntaxError, e:
         msg = "Cannot parse descriptor: %r\nException: %r"
         raise ValueError(msg % (s, e))
开发者ID:ska-sa,项目名称:PySPEAD,代码行数:13,代码来源:spead.py


示例9: load

def load(file, metafile=None):
    """Open a .npy file and load it into memory as an info_aray.

    Similar to the numpy.load function.  Does not support memory
    mapping (use open_memmap).

    Parameters
    ----------
    file: file handle or str
        .npy file or file name to read the array from.
    metafile: str
        File name for which the `info` attribute of the returned InfoArray
        will be read from. Default is None, where the it is
        assumed to be the file name associated with `file` with ".meta"
        appended. If the file does not exist, the info attribute is initialized
        to an empty dictionary.

    Returns
    -------
    iarray: InfoArray object
    """

    # Load the data from .npy format.
    array = sp.load(file)

    # Figure out what the filename for the meta data should be.
    if metafile is None:
        try:
            fname = file.name
        except AttributeError:
            fname = file
        metafile = fname + ".meta"

    # Read the meta data.
    if os.path.isfile(metafile):
        info_fid = open(metafile, 'r')
        try:
            infostring = info_fid.readline()
        finally:
            info_fid.close()
        info = safe_eval(infostring)
    else:
        info = {}

    # Construct the infor array.
    array = info_header.InfoArray(array, info)

    return array
开发者ID:eric-switzer,项目名称:algebra_base,代码行数:48,代码来源:file_io.py


示例10: test_safe_eval_nameconstant

def test_safe_eval_nameconstant():
    # Test if safe_eval supports Python 3.4 _ast.NameConstant
    utils.safe_eval('None')
开发者ID:Razin-Tailor,项目名称:ChatterBot,代码行数:3,代码来源:test_utils.py


示例11: read_array_header_1_0

def read_array_header_1_0(fp):
    """
    Read an array header from a filelike object using the 1.0 file format
    version.

    This will leave the file object located just after the header.

    Parameters
    ----------
    fp : filelike object
        A file object or something with a `.read()` method like a file.

    Returns
    -------
    shape : tuple of int
        The shape of the array.
    fortran_order : bool
        The array data will be written out directly if it is either C-contiguous
        or Fortran-contiguous. Otherwise, it will be made contiguous before
        writing it out.
    dtype : dtype
        The dtype of the file's data.

    Raises
    ------
    ValueError
        If the data is invalid.

    """
    # Read an unsigned, little-endian short int which has the length of the
    # header.
    import struct
    hlength_str = fp.read(2)
    if len(hlength_str) != 2:
        msg = "EOF at %s before reading array header length"
        raise ValueError(msg % fp.tell())
    header_length = struct.unpack('<H', hlength_str)[0]
    header = fp.read(header_length)
    if len(header) != header_length:
        raise ValueError("EOF at %s before reading array header" % fp.tell())

    # The header is a pretty-printed string representation of a literal Python
    # dictionary with trailing newlines padded to a 16-byte boundary. The keys
    # are strings.
    #   "shape" : tuple of int
    #   "fortran_order" : bool
    #   "descr" : dtype.descr
    try:
        d = safe_eval(header)
    except SyntaxError as e:
        msg = "Cannot parse header: %r\nException: %r"
        raise ValueError(msg % (header, e))
    if not isinstance(d, dict):
        msg = "Header is not a dictionary: %r"
        raise ValueError(msg % d)
    keys = sorted(d.keys())
    if keys != ['descr', 'fortran_order', 'shape']:
        msg = "Header does not contain the correct keys: %r"
        raise ValueError(msg % (keys,))

    # Sanity-check the values.
    if (not isinstance(d['shape'], tuple) or
        not numpy.all([isinstance(x, (int,long)) for x in d['shape']])):
        msg = "shape is not valid: %r"
        raise ValueError(msg % (d['shape'],))
    if not isinstance(d['fortran_order'], bool):
        msg = "fortran_order is not a valid bool: %r"
        raise ValueError(msg % (d['fortran_order'],))
    try:
        dtype = numpy.dtype(d['descr'])
    except TypeError as e:
        msg = "descr is not a valid dtype descriptor: %r"
        raise ValueError(msg % (d['descr'],))

    return d['shape'], d['fortran_order'], dtype
开发者ID:adalke,项目名称:numpy,代码行数:75,代码来源:format.py



注:本文中的numpy.lib.utils.safe_eval函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python linalg.cholesky函数代码示例发布时间:2022-05-27
下一篇:
Python type_check.nan_to_num函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap