Exemplo n.º 1
0
def find_dataframe(mxd, name=None, case_sensitive=False):
    """
    Finds a data frame by its (case-insensitive) name in the given ArcMap document (MXD) and returns it.
    If no *name* is specified, the active data frame in the given Map Document is returned.
    If no data frame was found at all, ``None`` is returned. This can only happen, when looking for a specific *name*.

    :param mxd:                 A :class:`arcpy.mapping.MapDocument` instance.
    :param name:                The name of the data frame to search for.
    :param case_sensitive:      If ``True``, the data frame name needs to match exactly.
                                If ``False`` (default), the data frame character case is ignored.
    :type mxd:                  arcpy.mapping.MapDocument
    :type name:                 str, unicode
    :type case_sensitive:       bool
    :rtype:                     arcpy._mapping.DataFrame

    .. seealso::                https://desktop.arcgis.com/en/arcmap/latest/analyze/arcpy-mapping/dataframe-class.htm
    """
    df_ref = None
    if isinstance(name, basestring):
        name = _tu.to_unicode(name if case_sensitive else name.lower())
        for df in _arcpy.mapping.ListDataFrames(mxd):
            df_name = df.name if case_sensitive else df.name.lower()
            if df_name == name:
                df_ref = df
                break
    else:
        df_ref = mxd.activeDataFrame
    return df_ref
Exemplo n.º 2
0
def find_layers(wildcard=None, mxd=None, dataframe=None):
    """
    Finds **all** layers that match a certain wild card expression in the specified ArcMap document (or current one).
    All matching layers are returned as a list of Layer instances. If no layers were found, an empty list is returned.

    :param wildcard:    Layer name search string (with wild card characters).
                        Unlike the :func:`find_layer` method, it is **not** possible to use a group layer prefix here.
                        Furthermore, the search string is case sensitive.
                        If this value is not specified, all layers in the map document will be returned.
    :param mxd:         The path to the ArcMap Document (MXD) or a MapDocument instance in which to find the layer(s).
                        If no MXD is specified, the search will take place in the current MXD (if any).
    :param dataframe:   The case-insensitive name of the data frame in which to find the layer(s).
                        If no data frame is specified and/or there is only 1 data frame,
                        the search will take place in the active data frame.
    :type wildcard:     str, unicode
    :type mxd:          str, unicode, arcpy.mapping.MapDocument
    :type dataframe:    str, unicode
    :rtype:             list
    :raises ValueError: If no map document was found.

    .. seealso::        https://desktop.arcgis.com/en/arcmap/latest/analyze/arcpy-mapping/layer-class.htm
    """
    wildcard = None if not wildcard else _tu.to_unicode(wildcard)
    mxd_ref, df_ref = _get_mxd_df(mxd, dataframe)

    return _arcpy.mapping.ListLayers(mxd_ref, wildcard, df_ref) or []
Exemplo n.º 3
0
def find_parent(path, name):
    """
    Finds within *path* the parent directory that contains a file or directory with the given *name*.
    Note that *path* and *name* values are matched case-insensitively, but the found path is returned
    in the original case (as a normalized path).

    If no matches have been found or if the match has no parent, an empty string is returned.
    If there are multiple matches, the parent path of the first match is returned.

    Examples:

        >>> find_parent('C:\\Projects\\parent\\LEVEL0\\level1\\level2.txt', 'level0')
        'C:\\Projects\\parent'
        >>> find_parent('C:\\Projects\\parent\\LEVEL\\level\\level.txt', 'level')
        'C:\\Projects\\parent'
        >>> find_parent('C:\\Projects\\some_dir', 'C:')
        ''
        >>> find_parent('C:\\Projects\\parent\\must_include_extension.txt', 'must_include_extension')
        ''

    :param path:    The path to search.
    :param name:    The name for which to search the parent directory in *path*.
                    This value can be a file name (with extension!) or a directory name.
                    Partial paths, pre- or suffixes or regular expressions are not allowed here and will return None.
    :type path:     str, unicode
    :type name:     str, unicode
    :rtype:         str, unicode
    """
    def match_parts(plist, n):
        # Search for n in plist and yield the parts up to n
        n_ci = n.lower()
        if n_ci not in (p.lower() for p in plist):
            return

        for p in plist:
            if p.lower() == n_ci:
                return
            yield p

    # Get path type (unicode or str) so we correctly join the path parts without encoding issues
    path_type = type(path)

    # Validate arguments
    _vld.pass_if(issubclass(path_type, basestring), TypeError,
                 'path attribute must be a string')
    _vld.pass_if(isinstance(name, basestring), TypeError,
                 'name attribute must be a string')

    # Split path into parts list, encode or decode name if name type does not match path type
    parts = normalize(path, False).split(_os.sep)
    if not isinstance(name, path_type):
        name = _tu.to_str(name) if isinstance(
            name, unicode) else _tu.to_unicode(name)

    # Return the concatenated path parts up til the match (or an empty string if nothing was found)
    return path_type(_os.sep).join(match_parts(parts, name)) or path_type(
        _const.CHAR_EMPTY)
Exemplo n.º 4
0
def test_tounicode():
    assert textutils.to_unicode(7) == u'7'
    assert textutils.to_unicode('test') == u'test'
    assert textutils.to_unicode('täst'.decode('utf8')) == 'täst'.decode('utf8')
    assert textutils.to_unicode('täst') == 'täst'.decode('utf8')
    assert textutils.to_unicode('täst'.decode('cp1252')) == 'täst'.decode('cp1252')
    assert textutils.to_unicode('täst', 'utf16') == u't\xc3\xa4st'
Exemplo n.º 5
0
    def _format_value(self, value):
        """
        Private method to format *value* for use in an SQL expression based on its type.
        This basically means that all non-numeric values (strings) will be quoted.
        If value is a :class:`gpf.common.guids.Guid` instance, the result will be wrapped in curly braces and quoted.

        :param value:   Any value. Single quotes in strings will be escaped automatically.
        :return:        A formatted string.
        :rtype:         unicode
        """
        if _vld.is_number(value, True):
            # Note: a `bool` is of instance `int` but calling format() on it will return a string (True or False).
            # To prevent this from happening, we'll use the `real` numeric part instead (on int, float and bool).
            return _tu.to_unicode(value.real, self._enc)

        if isinstance(value, _guids.Guid):
            # Parse Guid instances as strings
            value = str(value)
        if _vld.is_text(value):
            return _tu.to_unicode(_tu.to_repr(value, self._enc), self._enc)

        raise ValueError(
            'All values in an SQL expression must be text strings or numeric values'
        )
Exemplo n.º 6
0
def find_layer(name, mxd=None, dataframe=None, case_sensitive=False):
    """
    Finds a **single** layer by its (case-insensitive) name in the specified ArcMap document (or current one).
    If the layer was not found, ``None`` is returned.

    :param name:            Name of the layer to find.
                            If the layer name exists multiple times in different group layers,
                            you can prefix the layer with the group layer name followed by a forward slash (/).
    :param mxd:             The path to the ArcMap Document (MXD) or a MapDocument instance in which to find the layer.
                            If no MXD is specified, the search will take place in the current MXD (if any).
    :param dataframe:       The name of the data frame in which to find the layer.
                            If no data frame is specified and/or there is only 1 data frame,
                            the search will take place in the active data frame.
    :param case_sensitive:  If ``True``, the layer name needs to match exactly.
                            If ``False`` (default), the layer character case is ignored.
                            Note that this setting also affects the *dataframe* argument, when specified.
    :type name:             str, unicode
    :type mxd:              str, unicode, arcpy.mapping.MapDocument
    :type dataframe:        str, unicode
    :type case_sensitive:   bool
    :rtype:                 arcpy.mapping.Layer
    :raises ValueError:     If no layer name was specified, or if no map document was found.

    .. seealso::            https://desktop.arcgis.com/en/arcmap/latest/analyze/arcpy-mapping/layer-class.htm
    """

    # Validation
    _vld.pass_if(_vld.has_value(name), ValueError,
                 'Layer name has not been specified')

    name = _tu.to_unicode(_paths.normalize(name, not case_sensitive))
    mxd_ref, df_ref = _get_mxd_df(mxd, dataframe, case_sensitive)

    # Find the layer by name
    for lyr in _arcpy.mapping.ListLayers(mxd_ref, data_frame=df_ref):
        lyr_name = lyr.name if case_sensitive else lyr.name.lower()
        if lyr_name == name or _paths.normalize(lyr.longName,
                                                not case_sensitive) == name:
            return lyr
    return None
Exemplo n.º 7
0
 def _add_field(self, field):
     """  Adds a field to the query (combine or init). """
     self._add_any(_tu.to_unicode(field, self._enc), True)
     self._isdirty = True