读取文件, 并返回内容,
        如果读取失败,返回None

    :param pth:
    :type pth:
    :return:
    :rtype:
493230
def read_file(pth, use_str=False):
    
    cont = None
    try:
        with open(u'' + pth, 'rb') as fp:
            cont = fp.read()

        if use_str:
            cont = to_str(cont)
    except Exception as err:
        print(err)
    return cont
845621
def _hugoniot_pth(self, v):
        
        temp = self._hugoniot_t(v)
        return self.cal_pth(v, temp)
795225
def pickle_m2f(dat, pth):
    
    mkdir_p(pth)
    # 为了2与3兼容, 设置 dump 的协议为 2
    with open(pth, 'wb') as f:
        pickle.dump(dat, f, 2)
743853
def _prt_txt_hdr(prt, prtfmt):
    """"""
    tblhdrs = get_fmtfldsdict(prtfmt)
    # If needed, reformat for format_string for header, which has strings, not floats.
    hdrfmt = re.sub(r':(\d+)\.\S+}', r':\1}', prtfmt)
    hdrfmt = re.sub(r':(0+)(\d+)}', r':\2}', hdrfmt)
    prt.write("#{}".format(hdrfmt.format(**tblhdrs)))
271876
def venv_pth(self, dirs):
        '''
        
        '''
        # Create venv.pth to add dirs to sys.path when using the virtualenv.
        text = StringIO.StringIO()
        text.write("# Autogenerated file.  Do not modify.\n")
        for path in dirs:
            text.write('{}\n'.format(path))
        put(text, os.path.join(self.site_packages_dir(), 'venv.pth'), mode=0664)
906808
def write(self, s):
        
        if not self.isalive():
            raise EOFError('Pty is closed')
        if PY2:
            s = _unicode(s)

        success, nbytes = self.pty.write(s)
        if not success:
            raise IOError('Write failed')
        return nbytes
565797
def fmt(self, po_file, mo_file):
        
        if not os.path.exists(po_file):
            slog.error('The PO file [%s] is non-existen!'%po_file)
            return
        txt = subprocess.check_output([self._msgfmt, 
            '--check', "--strict", '--verbose', 
            "--output-file", mo_file, po_file], 
                stderr=subprocess.STDOUT, 
                universal_newlines=True)
        slog.info(txt)
599215
def content_type(self, mime_type: Optional[MimeType] = None) -> str:
        
        fmt = self.__file.mime_type(type_=mime_type)
        return 'Content-Type: {}'.format(fmt)
255396
def get_content_type (headers):
    
    ptype = headers.get('Content-Type', 'application/octet-stream')
    if ";" in ptype:
        # split off not needed extension info
        ptype = ptype.split(';')[0]
    return ptype.strip().lower()
1288432
def _getpwnam(name, root=None):
    '''
    
    '''
    root = '/' if not root else root
    passwd = os.path.join(root, 'etc/passwd')
    with salt.utils.files.fopen(passwd) as fp_:
        for line in fp_:
            line = salt.utils.stringutils.to_unicode(line)
            comps = line.strip().split(':')
            if comps[0] == name:
                # Generate a getpwnam compatible output
                comps[2], comps[3] = int(comps[2]), int(comps[3])
                return pwd.struct_passwd(comps)
    raise KeyError
1001106
def in6_ptoc(addr):
    
    try:
        d = struct.unpack("!IIII", inet_pton(socket.AF_INET6, addr))
    except Exception:
        return None
    res = 0
    m = [2**96, 2**64, 2**32, 1]
    for i in range(4):
        res += d[i] * m[i]
    rem = res
    res = []
    while rem:
        res.append(_rfc1924map[rem % 85])
        rem = rem // 85
    res.reverse()
    return "".join(res)
902824
def process_path(label, pth):
   ""
   
   if pth is None:
      sys.exit("no %s path given" % label)
      
   if pth.startswith("/"):
      pass
   elif pth[0] in (".", "~"):
      pth = os.path.realpath(pth)
   else:
      pth = os.getcwd() + os.sep + pth
   
   if not os.path.exists(pth):
      sys.exit("%s path %s does not exist" % (label, pth))

   return pth
452628
def read_header(cls, headers_path, block_height, allow_none=False):
        
        if os.path.exists(headers_path):
    
            header_parser = BlockHeaderSerializer()
            sb = os.stat( headers_path )
            if sb.st_size < BLOCK_HEADER_SIZE * block_height:
                # beyond EOF 
                if allow_none:
                    return None 
                else:
                    raise Exception('EOF on block headers')

            with open( headers_path, "rb" ) as f:
                f.seek( block_height * BLOCK_HEADER_SIZE, os.SEEK_SET )
                hdr = SPVClient.read_header_at( f )

            return hdr
        else:
            if allow_none:
                return None
            else:
                raise Exception('No such file or directory: {}'.format(headers_path))
625973
def folder_size(pth, ignore=None):
    
    if not os.path.isdir(pth):
        raise exc.FolderNotFound

    ignore = coerce_to_list(ignore)

    total = 0
    for root, _, names in os.walk(pth):
        paths = [os.path.realpath(os.path.join(root, nm)) for nm in names]
        for pth in paths[::-1]:
            if not os.path.exists(pth):
                paths.remove(pth)
            elif match_pattern(pth, ignore):
                paths.remove(pth)
        total += sum(os.stat(pth).st_size for pth in paths)

    return total
977218
def glob(self, pat):
        
        r = ""
        negate = int(pat.startswith('!'))
        i = negate

        while i < len(pat):
            if pat[i:i + 3] == '**/':
                r += "(?:.*/)?"
                i += 3
            elif pat[i] == "*":
                r += "[^/]*"
                i += 1
            elif pat[i] == ".":
                r += "[.]"
                i += 1
            elif pat[i] == "?":
                r += "."
                i += 1
            else:
                r += pat[i]
                i += 1
        r += r'\Z(?ms)'
        # print '\n\npat', pat
        # print 'regex:', r
        # print [s.relpath(self).replace('\\', '/') for s in self]
        rx = re.compile(r)

        def match(d):
            m = rx.match(d)
            return not m if negate else m

        return [s for s in self if match(s.relpath(self).replace('\\', '/'))]
679934
function (p, cb) {
				var pth = p.replace(/\\\?/g, '\/'); // Glob must use / as path seperator even on windows
				glob(pth + '/**/*.*', function (er, files) {
					if (er) {
						return cb(er);
					}
					return cb(null, files.map(function (f) {
						return path.relative(p, f);
					}));
				});
			}
678668
def get_pandoc_formats():
    
    try:
        p = subprocess.Popen(
            ['pandoc', '-h'],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE)
    except OSError:
        raise OSError("You probably do not have pandoc installed.")

    help_text = p.communicate()[0].decode().splitlines(False)
    txt = ' '.join(help_text[1:help_text.index('Options:')])

    aux = txt.split('Output formats: ')
    in_ = aux[0].split('Input formats: ')[1].split(',')
    out = aux[1].split(',')

    return [f.strip() for f in in_], [f.strip() for f in out]