Python types.FileType() Examples

The following are code examples for showing how to use types.FileType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: girlfriend   Author: chihongze   File: mail.py    MIT License 6 votes vote down vote up
def __init__(self, attachment_file, mime_type, attachment_filename=None):
        """
        :param attachment_file  作为附件的文件对象,可以是file对象或者StringIO对象,
                                如果是字符串,那么将作为文件路径进行加载
        :param mime_type  附件的mime type,比如application/octet-stream
        :param attachment_filename  附件所使用的文件名
        """
        if attachment_filename is None:
            if isinstance(attachment_file, types.StringTypes):
                self._attachment_filename = os.path.split(
                    attachment_file)[1]
            elif isinstance(attachment_file, types.FileType):
                self._attachment_filename = os.path.split(
                    attachment_file.name)[1]
            else:
                raise InvalidArgumentException(
                    u"必须制定attachement_filename参数作为附件文件名") 
Example 2
Project: libvirt-test-API   Author: libvirt   File: xml_parser.py    GNU General Public License v2.0 6 votes vote down vote up
def parse(self, arg):
        out = None
        if sys.version_info[0] >= 3:
            from io import IOBase
            filetype = IOBase
        else:
            filetype = types.FileType
        if isinstance(arg, filetype):
            out = self.parsefile(arg)
        elif os.path.exists(arg):
            print("file: %s " % arg)
            out = self.parsefile(arg)
        else:
            streamstr = StringIO(arg)
            out = self.parsefile(streamstr)
        if out is not None:
            return out 
Example 3
Project: pyblish-win   Author: pyblish   File: pydoc.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 4
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 5 votes vote down vote up
def uploadFile(self, newFile, lockToken=None):
        """
        Write binary data to permanent storage.
        
        @param newFile: File containing binary data.
        @param lockToken: None or lock token from last lock request
        @type  lockToken: L{LockToken}
        """
        assert isinstance(newFile, types.FileType), "Argument is no file: " + file.__class__.__name__
        assert lockToken == None or isinstance(lockToken, LockToken), \
                "Invalid lockToken argument %s" % type(lockToken)
        header = {}
        if lockToken:
            header = lockToken.toHeader()
        self.connection.putFile(self.path, newFile, header=header) 
Example 5
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: c_spec.py    GNU General Public License v3.0 5 votes vote down vote up
def init_info(self):
        common_base_converter.init_info(self)
        self.type_name = 'file'
        self.check_func = 'PyFile_Check'
        self.c_type = 'FILE*'
        self.return_type = self.c_type
        self.to_c_return = "PyFile_AsFile(py_obj)"
        self.headers = ['<stdio.h>']
        self.matching_types = [types.FileType] 
Example 6
Project: ironpython2   Author: IronLanguages   File: pydoc.py    Apache License 2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 7
Project: code-inspector   Author: maxim5   File: 6ad4f63fd0366f96e58fc5a9c62fa761_algorithm.py    Apache License 2.0 5 votes vote down vote up
def OpenGraph(self, file_obj, fileName=None):
        """ Read in a graph from file and open the display """
        if type(file_obj) in types.StringTypes:
            self.graphFileName = file_obj
        elif type(file_obj)==types.FileType or issubclass(file_obj.__class__,StringIO.StringIO):
            self.graphFileName = fileName
        else:
            raise Exception("wrong types in argument list: expected string or file like object")
        self.cleanGraphCopy = OpenCATBoxGraph(file_obj)
        self.restoreGraph()
        self.GUI.graphDisplay.Show() # In case we are hidden
        self.GUI.graphDisplay.ShowGraph(self.graph, stripPath(self.graphFileName))
        self.GUI.graphDisplay.RegisterGraphInformer(WeightedGraphInformer(self.graph))
        self.GUI.graphDisplay.UpdateScrollRegion(auto=1) 
Example 8
Project: IronHydra   Author: microdee   File: pydoc.py    MIT License 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 9
Project: Computable   Author: ktraunmueller   File: pydoc.py    MIT License 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 10
Project: Computable   Author: ktraunmueller   File: c_spec.py    MIT License 5 votes vote down vote up
def init_info(self):
        common_base_converter.init_info(self)
        self.type_name = 'file'
        self.check_func = 'PyFile_Check'
        self.c_type = 'FILE*'
        self.return_type = self.c_type
        self.to_c_return = "PyFile_AsFile(py_obj)"
        self.headers = ['<stdio.h>']
        self.matching_types = [types.FileType] 
Example 11
Project: oss-ftp   Author: aliyun   File: pydoc.py    MIT License 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 12
Project: poker   Author: surgebiswas   File: c_spec.py    MIT License 5 votes vote down vote up
def init_info(self):
        common_base_converter.init_info(self)
        self.type_name = 'file'
        self.check_func = 'PyFile_Check'
        self.c_type = 'FILE*'
        self.return_type = self.c_type
        self.to_c_return = "PyFile_AsFile(py_obj)"
        self.headers = ['<stdio.h>']
        self.matching_types = [types.FileType] 
Example 13
Project: godot-zeronet-plugin   Author: zam-org   File: pydoc.py    GNU General Public License v2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 14
Project: godot-zeronet-plugin   Author: zam-org   File: pydoc.py    GNU General Public License v2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 15
Project: godot-zeronet-plugin   Author: zam-org   File: pydoc.py    GNU General Public License v2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 16
Project: godot-zeronet-plugin   Author: zam-org   File: pydoc.py    GNU General Public License v2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 17
Project: godot-zeronet-plugin   Author: zam-org   File: pydoc.py    GNU General Public License v2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 18
Project: qgis-wps4server   Author: 3liz   File: InAndOutputs.py    GNU General Public License v3.0 5 votes vote down vote up
def setValue(self, value):
        """Set the output value

        :param value: value to be returned (file name or file itself)
        :type value: string or file
        """

        # Note: cStringIO and StringIO are totally messed up, StringIO is type instance, cString is type cStringIO.StringO
        # Better to also use __class__.__name__ to be certain what is is
        # StringIO => StringIO but cStringIO => StringO
        if type(value) == types.StringType or type(value) == types.UnicodeType:
            self.value = value
        elif type(value) == types.FileType:
            self.value = value.name
        elif value.__class__.__name__ == 'StringIO' or value.__class__.__name__ == 'StringO':
            import tempfile
            from os import curdir
            # (5, '/tmp/pywps-instanceS2j6ve/pywpsOutputZxSM6V')
            stringIOName = tempfile.mkstemp(prefix="pywpsOutput", dir=curdir)
            stringIOName = stringIOName[1]

            stringIOFile = open(stringIOName, "w")
            stringIOFile.write(value.getvalue())
            stringIOFile.close()
            self.value = stringIOName
        # TODO add more types, like Arrays and lists for example
        else:
            raise Exception("Output type '%s' of '%s' output not known, not FileName, File or (c)StringIO object" %
                            (type(value), self.identifier)) 
Example 19
Project: qgis-wps4server   Author: 3liz   File: Post.py    GNU General Public License v3.0 5 votes vote down vote up
def parse(self, file):
        """Parse parameters stored as XML file

        :param file: input file object or class:`java.io.BufferedReader`
        :return: parsed input object
        """

        maxFileSize = None
        inputXml = None

        # get the maximal input file size from configuration
        maxFileSize = self.getMaxFileSize(
            pywps.config.getConfigValue("server", "maxFileSize").lower())

        # read the document
        if OSNAME == "java" and\
                type(file) != types.FileType:
            inputXml = ""
            while 1:
                line = file.readLine()
                if not line:
                    break
                inputXml += line
                # TODO:
                # if maxFileSize > 0 and\
                #    inputXml.__sizeof__() > maxFileSize:
                #    raise pywps.FileSizeExceeded()
            # make DOM from XML
            import org.xml.sax.SAXException
            try:
                self.document = parseString(inputXml)
            except org.xml.sax.SAXException, e:
                raise pywps.NoApplicableCode(e.message) 
Example 20
Project: qgis-wps4server   Author: 3liz   File: response.py    GNU General Public License v3.0 5 votes vote down vote up
def _printResponseModPython(request, response, contentType="application/xml"):

    if contentType:
        request.content_type = contentType

    if type(response) == types.FileType:
        request.write(response.read())
    else:
        request.write(response) 
Example 21
Project: qgis-wps4server   Author: 3liz   File: response.py    GNU General Public License v3.0 5 votes vote down vote up
def _printResponseFile(fileOut, response, contentType="application/xml"):

    if fileOut == STDOUT and contentType:
        print "Content-Type: %s\n" % contentType
    elif fileOut.closed:
        fileOut = open(fileOut.name, "w")

    if type(response) == types.FileType:
        fileOut.write(response.read())
    else:
        fileOut.write(response)
    fileOut.flush()

    if fileOut != STDOUT:
        fileOut.close() 
Example 22
Project: qgis-wps4server   Author: 3liz   File: response.py    GNU General Public License v3.0 5 votes vote down vote up
def _printResponseJava(resp, response, contentType="application/xml"):
    if contentType:
        resp.setContentType(contentType)
    toClient = resp.getWriter()

    if type(response) == types.FileType:
        toClient.println(response.read())
    else:
        toClient.println(response) 
Example 23
Project: tichu-tournament   Author: aragos   File: utils.py    MIT License 5 votes vote down vote up
def isNonPrimitiveInstance(x):
        return isinstance(x,types.InstanceType) or not isinstance(x,(float,int,long,type,tuple,list,dict,bool,unicode,str,buffer,complex,slice,types.NoneType,
                    types.FunctionType,types.LambdaType,types.CodeType,types.GeneratorType,
                    types.ClassType,types.UnboundMethodType,types.MethodType,types.BuiltinFunctionType,
                    types.BuiltinMethodType,types.ModuleType,types.FileType,types.XRangeType,
                    types.TracebackType,types.FrameType,types.EllipsisType,types.DictProxyType,
                    types.NotImplementedType,types.GetSetDescriptorType,types.MemberDescriptorType
                    )) 
Example 24
Project: KalutClient   Author: TwoUnderscorez   File: pydoc.py    Apache License 2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 25
Project: PCTRL   Author: USTC-INFINITELAB   File: pox-pydoc.py    Apache License 2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 26
Project: kinect-2-libras   Author: inessadl   File: pydoc.py    Apache License 2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 27
Project: Savethemblobs_app   Author: iApeiron   File: pydoc.py    MIT License 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 28
Project: girlfriend   Author: chihongze   File: mail.py    MIT License 5 votes vote down vote up
def _gen_payload(self):
        # 文件类型的情况
        if isinstance(self._attachment_file, types.FileType):
            try:
                return self._attachment_file.read()
            finally:
                self._attachment_file.close()
        # 字符串路径的情况
        elif isinstance(self._attachment_file, types.StringTypes):
            with open(self._attachment_file, "r") as f:
                return f.read()
        # StringIO or cStringIO
        else:
            self._attachment_file.seek(0)
            return self._attachment_file.read() 
Example 29
Project: Wallet   Author: superbitcoin   File: pydoc.py    MIT License 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 30
Project: sdn-d2d   Author: mathwuyue   File: pox-pydoc.py    Apache License 2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 31
Project: Hot   Author: dsolimando   File: pydoc.py    GNU General Public License v3.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if sys.platform.startswith('java'):
        return plainpager
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more %s' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 32
Project: Hot   Author: dsolimando   File: modjy_impl.py    GNU General Public License v3.0 5 votes vote down vote up
def deal_with_app_return(self, environ, start_response_callable, app_return):
        self.log.debug("Processing app return type: %s" % str(type(app_return)))
        if isinstance(app_return, types.StringTypes):
            raise ReturnNotIterable("Application returned object that was not an iterable: %s" % str(type(app_return)))
        if type(app_return) is types.FileType:
            pass # TBD: What to do here? can't call fileno()
        if hasattr(app_return, '__len__') and callable(app_return.__len__):
            expected_pieces = app_return.__len__()
        else:
            expected_pieces = -1
        try:
            try:
                ix = 0
                for next_piece in app_return:
                    if not isinstance(next_piece, types.StringTypes):
                        raise NonStringOutput("Application returned iterable containing non-strings: %s" % str(type(next_piece)))
                    if ix == 0:
                        # The application may have called start_response in the first iteration
                        if not start_response_callable.called:
                            raise StartResponseNotCalled("Start_response callable was never called.")
                        if not start_response_callable.content_length \
                            and expected_pieces == 1 \
                            and start_response_callable.write_callable.num_writes == 0:
                                # Take the length of the first piece
                                start_response_callable.set_content_length(len(next_piece))
                    start_response_callable.write_callable(next_piece)
                    ix += 1
                    if ix == expected_pieces:
                        break
                if expected_pieces != -1 and ix != expected_pieces:
                    raise WrongLength("Iterator len() was wrong. Expected %d pieces: got %d" % (expected_pieces, ix) )
            except AttributeError, ax:
                if str(ax) == "__getitem__":
                    raise ReturnNotIterable("Application returned object that was not an iterable: %s" % str(type(app_return)))
                else:
                    raise ax
            except TypeError, tx:
                raise ReturnNotIterable("Application returned object that was not an iterable: %s" % str(type(app_return))) 
Example 33
Project: linux-cross-gcc   Author: nmercier   File: pydoc.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(pager) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'pager')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 34
Project: linux-cross-gcc   Author: nmercier   File: pydoc.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 35
Project: AREPL-backend   Author: Almenon   File: pickler.py    MIT License 5 votes vote down vote up
def _flatten_file(self, obj):
        """
        Special case file objects
        """
        assert not PY3 and isinstance(obj, types.FileType)
        return None 
Example 36
Project: adv-net-samples   Author: gwAdvNet2015   File: pox-pydoc.py    MIT License 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 37
Project: kkFileView   Author: kekingcn   File: pydoc.py    Apache License 2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 38
Project: Splunking-Crime   Author: nccgroup   File: pydoc.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not hasattr(sys.stdin, "isatty"):
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 39
Project: lambda-OCRmyPDF   Author: chronograph-pe   File: utils.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def isNonPrimitiveInstance(x):
        return isinstance(x,types.InstanceType) or not isinstance(x,(float,int,long,type,tuple,list,dict,bool,unicode,str,buffer,complex,slice,types.NoneType,
                    types.FunctionType,types.LambdaType,types.CodeType,types.GeneratorType,
                    types.ClassType,types.UnboundMethodType,types.MethodType,types.BuiltinFunctionType,
                    types.BuiltinMethodType,types.ModuleType,types.FileType,types.XRangeType,
                    types.TracebackType,types.FrameType,types.EllipsisType,types.DictProxyType,
                    types.NotImplementedType,types.GetSetDescriptorType,types.MemberDescriptorType
                    )) 
Example 40
Project: senior-design   Author: james-tate   File: pydoc.py    GNU General Public License v2.0 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 41
Project: python-compat-runtime   Author: GoogleCloudPlatform   File: sandbox.py    Apache License 2.0 5 votes vote down vote up
def _install_fake_file(config, python_lib_paths, path_override_hook):
  """Install a stub file implementation to enforce sandbox rules."""
  stubs.FakeFile.set_allowed_paths(config.application_root,
                                   python_lib_paths[1:] +
                                   path_override_hook.extra_accessible_paths)
  stubs.FakeFile.set_skip_files(config.skip_files)
  stubs.FakeFile.set_static_files(config.static_files)
  __builtin__.file = stubs.FakeFile
  __builtin__.open = stubs.FakeFile
  types.FileType = stubs.FakeFile 
Example 42
Project: laboratoria   Author: almeidaw   File: pickler.py    Apache License 2.0 5 votes vote down vote up
def _flatten_file(self, obj):
        """
        Special case file objects
        """
        assert not PY3 and isinstance(obj, types.FileType)
        return None 
Example 43
Project: laboratoria   Author: almeidaw   File: pickler.py    Apache License 2.0 5 votes vote down vote up
def _flatten_file(self, obj):
        """
        Special case file objects
        """
        assert not PY3 and isinstance(obj, types.FileType)
        return None 
Example 44
Project: qgis-wps4server   Author: 3liz   File: response.py    GNU General Public License v3.0 4 votes vote down vote up
def response(response, targets, soapVersion=None, isSoap=False, isSoapExecute=False, contentType="application/xml", isPromoteStatus=False):
    """
    Print response to files given as input parameter.

    :param targets: file object or list of file objects. File name,
        mod_python request or java servlet response
    :type targets: string or list, 
    :param isSoap: print the response in SOAP envelope
    :type isSoap: bool
    :param response: the response object 
    :type response: file or string
    """

    # convert single file to array
    if type(targets) != type([]):
        targets = [targets]
    if isSoap:
        soap = Soap.SOAP()
        response = soap.getResponse(
            response, soapVersion, isSoapExecute, isPromoteStatus)

    if isinstance(response, Exceptions.WPSException):
        response = response.__str__()

    # for each file in file descriptor
    for f in targets:

        # consider, if this CGI, mod_python or Java requested output
        # mod_python here
        if repr(type(f)) == "<type 'mp_request'>":
            _printResponseModPython(f, response, contentType)

        # file object (output, or sys.stdout)
        elif types.FileType == type(f):
            _printResponseFile(f, response, contentType)

        # pywps.Ftp.FTP object
        elif isinstance(f, pywps.Ftp.FTP):
            _sendResponseFTP(f, response)
            logging.debug("Response document successfuly send to ftp server")

        # java servlet response
        elif OSNAME == "java":
            _printResponseJava(f, response, contentType)

        # close and open again, if it is a file
        if type(response) == types.FileType:
            response.close()
            response = open(response.name, "rb") 
Example 45
Project: AREPL-backend   Author: Almenon   File: pickler.py    MIT License 4 votes vote down vote up
def _get_flattener(self, obj):

        if PY2 and isinstance(obj, types.FileType):
            return self._flatten_file

        if util.is_bytes(obj):
            return self._flatten_bytestring

        if util.is_primitive(obj):
            return lambda obj: obj

        # Decimal is a primitive when use_decimal is True
        if self._use_decimal and isinstance(obj, decimal.Decimal):
            return lambda obj: obj

        list_recurse = self._list_recurse

        if util.is_list(obj):
            if self._mkref(obj):
                return list_recurse
            else:
                self._push()
                return self._getref

        # We handle tuples and sets by encoding them in a "(tuple|set)dict"
        if util.is_tuple(obj):
            if not self.unpicklable:
                return list_recurse
            return lambda obj: {tags.TUPLE: [self._flatten(v) for v in obj]}

        if util.is_set(obj):
            if not self.unpicklable:
                return list_recurse
            return lambda obj: {tags.SET: [self._flatten(v) for v in obj]}

        if util.is_dictionary(obj):
            return self._flatten_dict_obj

        if util.is_type(obj):
            return _mktyperef

        if util.is_object(obj):
            return self._ref_obj_instance

        if util.is_module_function(obj):
            return self._flatten_function

        # instance methods, lambdas, old style classes...
        self._pickle_warning(obj)
        return None 
Example 46
Project: python-for-android   Author: kuri65536   File: reflect.py    Apache License 2.0 4 votes vote down vote up
def objgrep(start, goal, eq=isLike, path='', paths=None, seen=None, showUnknowns=0, maxDepth=None):
    '''An insanely CPU-intensive process for finding stuff.
    '''
    if paths is None:
        paths = []
    if seen is None:
        seen = {}
    if eq(start, goal):
        paths.append(path)
    if id(start) in seen:
        if seen[id(start)] is start:
            return
    if maxDepth is not None:
        if maxDepth == 0:
            return
        maxDepth -= 1
    seen[id(start)] = start
    if isinstance(start, types.DictionaryType):
        for k, v in start.items():
            objgrep(k, goal, eq, path+'{'+repr(v)+'}', paths, seen, showUnknowns, maxDepth)
            objgrep(v, goal, eq, path+'['+repr(k)+']', paths, seen, showUnknowns, maxDepth)
    elif isinstance(start, (list, tuple, deque)):
        for idx in xrange(len(start)):
            objgrep(start[idx], goal, eq, path+'['+str(idx)+']', paths, seen, showUnknowns, maxDepth)
    elif isinstance(start, types.MethodType):
        objgrep(start.im_self, goal, eq, path+'.im_self', paths, seen, showUnknowns, maxDepth)
        objgrep(start.im_func, goal, eq, path+'.im_func', paths, seen, showUnknowns, maxDepth)
        objgrep(start.im_class, goal, eq, path+'.im_class', paths, seen, showUnknowns, maxDepth)
    elif hasattr(start, '__dict__'):
        for k, v in start.__dict__.items():
            objgrep(v, goal, eq, path+'.'+k, paths, seen, showUnknowns, maxDepth)
        if isinstance(start, types.InstanceType):
            objgrep(start.__class__, goal, eq, path+'.__class__', paths, seen, showUnknowns, maxDepth)
    elif isinstance(start, weakref.ReferenceType):
        objgrep(start(), goal, eq, path+'()', paths, seen, showUnknowns, maxDepth)
    elif (isinstance(start, types.StringTypes+
                    (types.IntType, types.FunctionType,
                     types.BuiltinMethodType, RegexType, types.FloatType,
                     types.NoneType, types.FileType)) or
          type(start).__name__ in ('wrapper_descriptor', 'method_descriptor',
                                   'member_descriptor', 'getset_descriptor')):
        pass
    elif showUnknowns:
        print 'unknown type', type(start), start
    return paths 
Example 47
Project: laboratoria   Author: almeidaw   File: pickler.py    Apache License 2.0 4 votes vote down vote up
def _get_flattener(self, obj):

        if PY2 and isinstance(obj, types.FileType):
            return self._flatten_file

        if util.is_bytes(obj):
            return self._flatten_bytestring

        if util.is_primitive(obj):
            return lambda obj: obj

        list_recurse = self._list_recurse

        if util.is_list(obj):
            if self._mkref(obj):
                return list_recurse
            else:
                self._push()
                return self._getref

        # We handle tuples and sets by encoding them in a "(tuple|set)dict"
        if util.is_tuple(obj):
            if not self.unpicklable:
                return list_recurse
            return lambda obj: {tags.TUPLE: [self._flatten(v) for v in obj]}

        if util.is_set(obj):
            if not self.unpicklable:
                return list_recurse
            return lambda obj: {tags.SET: [self._flatten(v) for v in obj]}

        if util.is_dictionary(obj):
            return self._flatten_dict_obj

        if util.is_type(obj):
            return _mktyperef

        if util.is_object(obj):
            return self._ref_obj_instance

        if util.is_module_function(obj):
            return self._flatten_function

        # instance methods, lambdas, old style classes...
        self._pickle_warning(obj)
        return None 
Example 48
Project: laboratoria   Author: almeidaw   File: pickler.py    Apache License 2.0 4 votes vote down vote up
def _get_flattener(self, obj):

        if PY2 and isinstance(obj, types.FileType):
            return self._flatten_file

        if util.is_bytes(obj):
            return self._flatten_bytestring

        if util.is_primitive(obj):
            return lambda obj: obj

        list_recurse = self._list_recurse

        if util.is_list(obj):
            if self._mkref(obj):
                return list_recurse
            else:
                self._push()
                return self._getref

        # We handle tuples and sets by encoding them in a "(tuple|set)dict"
        if util.is_tuple(obj):
            if not self.unpicklable:
                return list_recurse
            return lambda obj: {tags.TUPLE: [self._flatten(v) for v in obj]}

        if util.is_set(obj):
            if not self.unpicklable:
                return list_recurse
            return lambda obj: {tags.SET: [self._flatten(v) for v in obj]}

        if util.is_dictionary(obj):
            return self._flatten_dict_obj

        if util.is_type(obj):
            return _mktyperef

        if util.is_object(obj):
            return self._ref_obj_instance

        if util.is_module_function(obj):
            return self._flatten_function

        # instance methods, lambdas, old style classes...
        self._pickle_warning(obj)
        return None