當前位置: 首頁>>代碼示例>>Python>>正文


Python magic.from_file方法代碼示例

本文整理匯總了Python中magic.from_file方法的典型用法代碼示例。如果您正苦於以下問題:Python magic.from_file方法的具體用法?Python magic.from_file怎麽用?Python magic.from_file使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在magic的用法示例。


在下文中一共展示了magic.from_file方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _load_index

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def _load_index(self):
        index_path = self.index_path()
        if not os.path.exists(index_path):
            return {}

        content_type = magic.from_file(index_path, mime=True)
        if content_type in ("application/json", "text/plain"):
            logger.debug("Detected %s encoding for reading index", content_type)
            method = open
        elif content_type in ("application/gzip", "application/x-gzip"):
            logger.debug("Detected gzip encoding for reading index")
            method = gzip.open
        else:
            raise ValueError("Index is of unknown type", content_type)

        with method(index_path, "rt") as fp:
            data = json.load(fp)
        return data 
開發者ID:MichaelAquilina,項目名稱:S4,代碼行數:20,代碼來源:local.py

示例2: scan

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def scan(self):
        logging.debug("Scanning %s" % self._path)
        if os.path.isfile(self._path):
            mime_type = magic.from_file(self._path, mime=True)
            self._files.append(File(self._path, mime_type))
            logging.debug('\t- full path: %s, mime_type: %s' % (os.path.abspath(self._path), mime_type))
        else:
            for root, subdirs, files in os.walk(self._path):
                for filename in files:
                    file_path = os.path.join(root, filename)
                    mime_type = magic.from_file(file_path, mime=True)

                    logging.debug('\t- full path: %s, mime_type: %s' % (file_path, mime_type))
                    self._files.append(File(file_path, mime_type))

        context = {'tokenizer': Tokenizer(), 'regex': RegexScanner(), 'ner': NERScanner()}
        for f in self._files:
            f.scan(context) 
開發者ID:tokern,項目名稱:piicatcher,代碼行數:20,代碼來源:files.py

示例3: _compute_default_properties

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def _compute_default_properties(self, hash_only=False):
        if not hash_only:
            self['names'] = [os.path.basename(self['filepath'])]
            self['detailed_type'] = magic.from_file(self['filepath'])
            self['mime'] = magic.from_file(self['filepath'], mime=True)
            self['size'] = os.path.getsize(self['filepath'])

        # Init antivirus status
        self['antivirus'] = {}

        for module in dispatcher.get_antivirus_modules():
            self['antivirus'][module.name] = False

        self._set_type(hash_only)

    # initialize all necessary values for hash analysis 
開發者ID:certsocietegenerale,項目名稱:fame,代碼行數:18,代碼來源:file.py

示例4: ela

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def ela(filename, output_path):
    print "****ELA is in BETA****"
    if magic.from_file(filename, mime=True) == "image/jpeg":
        quality_level = 85
        tmp_img = os.path.join(output_path,os.path.basename(filename)+".tmp.jpg")
        ela = os.path.join(output_path,os.path.basename(filename)+".ela.jpg")
        image = Image.open(filename)
        image.save(tmp_img, 'JPEG', quality=quality_level)
        tmp_img_file = Image.open(tmp_img)
        ela_image = ImageChops.difference(image, tmp_img_file)
        extrema = ela_image.getextrema()
        max_diff = max([ex[1] for ex in extrema])
        scale = 255.0/max_diff
        ela_image = ImageEnhance.Brightness(ela_image).enhance(scale)
        ela_image.save(ela)
        os.remove(tmp_img)
    else:
        print "ELA works only with JPEG"


#Modified version of a gist by: https://github.com/erans 
開發者ID:redaelli,項目名稱:imago-forensics,代碼行數:23,代碼來源:extractor.py

示例5: get_type

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def get_type(self):
        try:
            ms = magic.open(magic.MAGIC_NONE)
            ms.load()
            file_type = ms.file(self.path)
        except:
            try:
                file_type = magic.from_file(self.path)
            except:
                try:
                    import subprocess
                    file_process = subprocess.Popen(['file', '-b', self.path], stdout = subprocess.PIPE)
                    file_type = file_process.stdout.read().strip()
                except:
                    return ''
        finally:
            try:
                ms.close()
            except:
                pass

        return file_type 
開發者ID:opensourcesec,項目名稱:CIRTKit,代碼行數:24,代碼來源:objects.py

示例6: create_spatial_resource

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def create_spatial_resource(sender, instance, created, **kwargs):
    if created or instance._original_url != instance.file.url:
        if instance.mime_type in GPX_MIME_TYPES:
            temp = io.ensure_dirs()
            with tempfile.NamedTemporaryFile(mode='wb', dir=temp) as f:
                instance_file = instance.file.open()
                f.write(instance_file.read())
                instance_file.close()
                f.seek(0)
                # need to double check the mime-type here as browser detection
                # of gpx mime type is not reliable
                mime_type = magic.from_file(f.name, mime=True)
                if mime_type in GPX_MIME_TYPES:
                    processor = GPXProcessor(f.name)
                    layers = processor.get_layers()
                    for layer in layers.keys():
                        if len(layers[layer]) > 0:
                            SpatialResource.objects.create(
                                resource=instance, name=layer,
                                geom=layers[layer])
                else:
                    raise InvalidGPXFile(
                        _("Invalid GPX mime type: {error}".format(
                            error=mime_type))
                    ) 
開發者ID:Cadasta,項目名稱:cadasta-platform,代碼行數:27,代碼來源:models.py

示例7: get_mime_type

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def get_mime_type(resource):
    import magic
    if resource.startswith('file://'):
        resource = resource[len('file://'):]

    if resource.startswith('http://') or resource.startswith('https://'):
        with urllib.request.urlopen(resource) as response:
            return response.info().get_content_type()
    else:
        if hasattr(magic, 'detect_from_filename'):
            mime = magic.detect_from_filename(resource)
        elif hasattr(magic, 'from_file'):
            mime = magic.from_file(resource, mime=True)
        else:
            raise RuntimeError('The installed magic version provides neither detect_from_filename nor from_file')

        if mime:
            return mime.mime_type 
開發者ID:BlackLight,項目名稱:platypush,代碼行數:20,代碼來源:__init__.py

示例8: qq_image_wrapper

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def qq_image_wrapper(self, data, chat: Chat = None):
        efb_msg = Message()
        if 'url' not in data:
            efb_msg.type = MsgType.Text
            efb_msg.text = self._('[Image Source missing]')
            return [efb_msg]

        efb_msg.file = cq_get_image(data['url'])
        if efb_msg.file is None:
            efb_msg.type = MsgType.Text
            efb_msg.text = self._('[Download image failed, please check on your QQ client]')
            return [efb_msg]

        efb_msg.type = MsgType.Image
        mime = magic.from_file(efb_msg.file.name, mime=True)
        if isinstance(mime, bytes):
            mime = mime.decode()
        efb_msg.filename = data['file'] if 'file' in data else efb_msg.file.name
        efb_msg.path = efb_msg.file.name
        efb_msg.mime = mime
        if "gif" in mime:
            efb_msg.type = MsgType.Animation
        return [efb_msg] 
開發者ID:milkice233,項目名稱:efb-qq-slave,代碼行數:25,代碼來源:MsgDecorator.py

示例9: qq_record_wrapper

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def qq_record_wrapper(self, data, chat: Chat = None):  # Experimental!
        efb_msg = Message()
        try:
            transformed_file = self.inst.coolq_api_query("get_record", file=data['file'], out_format='mp3')
            efb_msg.type = MsgType.Audio
            efb_msg.file = download_voice(transformed_file['file'],
                                          self.inst.client_config['api_root'].rstrip("/"),
                                          self.inst.client_config['access_token'])
            mime = magic.from_file(efb_msg.file.name, mime=True)
            if isinstance(mime, bytes):
                mime = mime.decode()
            efb_msg.path = efb_msg.file.name
            efb_msg.mime = mime
        except Exception:
            efb_msg.type = MsgType.Unsupported
            efb_msg.text = self._('[Voice Message] Please check it on your QQ')
            logging.getLogger(__name__).exception("Failed to download voice")
        return [efb_msg] 
開發者ID:milkice233,項目名稱:efb-qq-slave,代碼行數:20,代碼來源:MsgDecorator.py

示例10: get_parser_for_path

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def get_parser_for_path(self, path, config_path):
        if config_path.mime:
            mime = config_path.mime
        else:
            mime = magic.from_file(path, mime=True)
        _, ext = os.path.splitext(path)

        if mime == "text/plain":
            if ext in [".yaml", ".yml"]:
                return parser.YamlFileParser(self.threatmodel)
            elif ext in [".json"]:
                return parser.YamlFileParser(self.threatmodel)
            elif ext in [".txt"]:
                return parser.TextFileParser(self.threatmodel)
            else:
                logger.warn("Unsupported file extension {} for mime type text/plain for file {}".format(ext, path))
                return None
        else:
            return parser.SourceFileParser(self.threatmodel, mime) 
開發者ID:threatspec,項目名稱:threatspec,代碼行數:21,代碼來源:app.py

示例11: get_plaintext_document_body

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def get_plaintext_document_body(fpath, keep_layout=False):
    """Given a file-path to a full-text, return a list of unicode strings
       whereby each string is a line of the fulltext.
       In the case of a plain-text document, this simply means reading the
       contents in from the file. In the case of a PDF however,
       this means converting the document to plaintext.
       It raises UnknownDocumentTypeError if the document is not a PDF or
       plain text.
       @param fpath: (string) - the path to the fulltext file
       @return: (list) of strings - each string being a line in the document.
    """
    textbody = []
    mime_type = magic.from_file(fpath, mime=True)

    if mime_type == "text/plain":
        with open(fpath, "r") as f:
            textbody = f.readlines()

    elif mime_type == "application/pdf":
        textbody = convert_PDF_to_plaintext(fpath, keep_layout)

    else:
        raise UnknownDocumentTypeError(mime_type)

    return textbody 
開發者ID:inspirehep,項目名稱:refextract,代碼行數:27,代碼來源:engine.py

示例12: _get_language

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def _get_language(self):
        file_type = file_cmd.from_file(self.path).lower()
        if file_type.startswith(self.CPP):
            return 'cpp'
        if self.PYTHON in file_type:
            return 'python'
        if self.name.endswith(self.LAUNCH):
            return 'launch'
        if self.name == self.PKG_XML:
            return 'package'
        if self.name.endswith(self.MSG):
            return 'msg'
        if self.name.endswith(self.SRV):
            return 'srv'
        if self.name.endswith(self.ACTION):
            return 'action'
        if self.name.endswith(self.YAML):
            return 'yaml'
        if self.name == self.CMAKELISTS:
            return 'cmake'
        return 'unknown' 
開發者ID:git-afsantos,項目名稱:haros,代碼行數:23,代碼來源:metamodel.py

示例13: Filesystem

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def Filesystem(path):
    filemagic = magic.from_file(path)
    if "ext2" in filemagic or "ext4" in filemagic:
        return Ext2_Ext4(path, filemagic)
    if "cpio" in filemagic:
        return Cpio(path, filemagic)
    if "tar" in filemagic:
        return Tar(path, filemagic)
    pred("UnknownFileSystem {}".format(filemagic))
    sys.exit(1) 
開發者ID:nongiach,項目名稱:arm_now,代碼行數:12,代碼來源:filesystem.py

示例14: inspect

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def inspect(self, sample):
        sample.info[self.NAME] = {"magic": magic.from_file(sample.path), "mime": magic.from_file(sample.path, mime = True)} 
開發者ID:Cisco-Talos,項目名稱:BASS,代碼行數:4,代碼來源:core.py

示例15: ftype

# 需要導入模塊: import magic [as 別名]
# 或者: from magic import from_file [as 別名]
def ftype(filename):
    type = magic.from_file(filename)
    return type 
開發者ID:alexandreborges,項目名稱:malwoverview,代碼行數:5,代碼來源:malwoverview.py


注:本文中的magic.from_file方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。