Uses default program defined by the system to open a file.

    References:
        http://stackoverflow.com/questions/2692873/quote-posix-shell-special-characters-in-python-output
972112
def startfile(fpath, detatch=True, quote=False, verbose=False, quiet=True):
    
    print('[cplat] startfile(%r)' % fpath)
    fpath = normpath(fpath)
    # print('[cplat] fpath=%s' % fpath)
    if not exists(fpath):
        raise Exception('Cannot start nonexistant file: %r' % fpath)
    #if quote:
    #    fpath = '"%s"' % (fpath,)
    if not WIN32:
        fpath = pipes.quote(fpath)
    if LINUX:
        #out, err, ret = cmd(['xdg-open', fpath], detatch=True)
        outtup = cmd(('xdg-open', fpath), detatch=detatch, verbose=verbose, quiet=quiet)
        #outtup = cmd('xdg-open', fpath, detatch=detatch)
    elif DARWIN:
        outtup = cmd(('open', fpath), detatch=detatch, verbose=verbose, quiet=quiet)
    elif WIN32:
        os.startfile(fpath)
    else:
        raise RuntimeError('Unknown Platform')
    if outtup is not None:
        out, err, ret = outtup
        if not ret:
            raise Exception(out + ' -- ' + err)
    pass
996272
def openfile(filename, mode="rt", *args, expanduser=False, expandvars=False,
             makedirs=False, **kwargs):
    """"""
    if filename in ("-", None):
        return sys.stdin if "r" in mode else sys.stdout
    if expanduser:
        filename = os.path.expanduser(filename)
    if expandvars:
        filename = os.path.expandvars(filename)
    if makedirs and ("a" in mode or "w" in mode):
        parentdir = os.path.dirname(filename)
        if not os.path.isdir(parentdir):
            os.makedirs(parentdir)
    if filename.endswith(".gz"):
        if gzip is None:
            raise NotImplementedError
        _open = gzip.open
    elif filename.endswith(".bz2"):
        if bz2 is None:
            raise NotImplementedError
        _open = bz2.open
    elif filename.endswith(".xz") or filename.endswith(".lzma"):
        if lzma is None:
            raise NotImplementedError
        _open = lzma.open
    else:
        _open = open
    return _open(filename, mode, *args, **kwargs)
763175
def main():
    
    usage = '%prog [options] "<input file>"'
    if '__main__.py' in sys.argv[0]: # python -m pyminifier
        usage = 'pyminifier [options] "<input file>"'
    parser = OptionParser(usage=usage, version=__version__)
    parser.disable_interspersed_args()
    parser.add_option(
        "-o", "--outfile",
        dest="outfile",
        default=None,
        help="Save output to the given file.",
        metavar="<file path>"
    )
    parser.add_option(
        "-d", "--destdir",
        dest="destdir",
        default="./minified",
        help=("Save output to the given directory. "
              "This option is required when handling multiple files. "
              "Defaults to './minified' and will be created if not present. "),
        metavar="<file path>"
    )
    parser.add_option(
        "--nominify",
        action="store_true",
        dest="nominify",
        default=False,
        help="Don't bother minifying (only used with --pyz).",
    )
    parser.add_option(
        "--use-tabs",
        action="store_true",
        dest="tabs",
        default=False,
        help="Use tabs for indentation instead of spaces.",
    )
    parser.add_option(
        "--bzip2",
        action="store_true",
        dest="bzip2",
        default=False,
        help=("bzip2-compress the result into a self-executing python script.  "
              "Only works on stand-alone scripts without implicit imports.")
    )
    parser.add_option(
        "--gzip",
        action="store_true",
        dest="gzip",
        default=False,
        help=("gzip-compress the result into a self-executing python script.  "
              "Only works on stand-alone scripts without implicit imports.")
    )
    if lzma:
        parser.add_option(
            "--lzma",
            action="store_true",
            dest="lzma",
            default=False,
            help=("lzma-compress the result into a self-executing python script.  "
                  "Only works on stand-alone scripts without implicit imports.")
        )
    parser.add_option(
        "--pyz",
        dest="pyz",
        default=None,
        help=("zip-compress the result into a self-executing python script. "
              "This will create a new file that includes any necessary implicit"
              " (local to the script) modules.  Will include/process all files "
              "given as arguments to pyminifier.py on the command line."),
        metavar="<name of archive>.pyz"
    )
    parser.add_option(
        "-O", "--obfuscate",
        action="store_true",
        dest="obfuscate",
        default=False,
        help=(
            "Obfuscate all function/method names, variables, and classes.  "
            "Default is to NOT obfuscate."
        )
    )
    parser.add_option(
        "--obfuscate-classes",
        action="store_true",
        dest="obf_classes",
        default=False,
        help="Obfuscate class names."
    )
    parser.add_option(
        "--obfuscate-functions",
        action="store_true",
        dest="obf_functions",
        default=False,
        help="Obfuscate function and method names."
    )
    parser.add_option(
        "--obfuscate-variables",
        action="store_true",
        dest="obf_variables",
        default=False,
        help="Obfuscate variable names."
    )
    parser.add_option(
        "--obfuscate-import-methods",
        action="store_true",
        dest="obf_import_methods",
        default=False,
        help="Obfuscate globally-imported mouled methods (e.g. 'Ag=re.compile')."
    )
    parser.add_option(
        "--obfuscate-builtins",
        action="store_true",
        dest="obf_builtins",
        default=False,
        help="Obfuscate built-ins (i.e. True, False, object, Exception, etc)."
    )
    parser.add_option(
        "--replacement-length",
        dest="replacement_length",
        default=1,
        help=(
            "The length of the random names that will be used when obfuscating "
            "identifiers."
        ),
        metavar="1"
    )
    parser.add_option(
        "--nonlatin",
        action="store_true",
        dest="use_nonlatin",
        default=False,
        help=(
            "Use non-latin (unicode) characters in obfuscation (Python 3 only)."
            "  WARNING: This results in some SERIOUSLY hard-to-read code."
        )
    )
    parser.add_option(
        "--prepend",
        dest="prepend",
        default=None,
        help=(
            "Prepend the text in this file to the top of our output.  "
            "e.g. A copyright notice."
        ),
        metavar="<file path>"
    )
    options, files = parser.parse_args()
    if not files:
        parser.print_help()
        sys.exit(2)
    pyminify(options, files)
704637
def file_or_stdin() -> Callable:
    

    def parse(path):
        if path is None or path == "-":
            return sys.stdin
        else:
            return data_io.smart_open(path)

    return parse
789565
def cmd():
    ''''''

    # Try to handle any reasonable thing thrown at this.
    # Consume '-f' and '-o' as input/output, allow '-' for stdin/stdout
    # and treat any subsequent arguments as a space separated string to
    # be titlecased (so it still works if people forget quotes)
    parser = argparse.ArgumentParser()
    in_group = parser.add_mutually_exclusive_group()
    in_group.add_argument('string', nargs='*', default=[],
            help='String to titlecase')
    in_group.add_argument('-f', '--input-file',
            help='File to read from to titlecase')
    parser.add_argument('-o', '--output-file',
            help='File to write titlecased output to)')

    args = parser.parse_args()

    if args.input_file is not None:
        if args.input_file == '-':
            ifile = sys.stdin
        else:
            ifile = open(args.input_file)
    else:
        ifile = sys.stdin

    if args.output_file is not None:
        if args.output_file == '-':
            ofile = sys.stdout
        else:
            ofile = open(args.output_file, 'w')
    else:
        ofile = sys.stdout

    if len(args.string) > 0:
        in_string = ' '.join(args.string)
    else:
        with ifile:
            in_string = ifile.read()

    with ofile:
        ofile.write(titlecase(in_string))
51137
def run_user_process(self, program, args, env):
        
        stdout_streams, stderr_streams = self._get_stdout_stderr_streams()

        if sys.platform == "win32":
            # PTYs don't work in windows so we use pipes.
            self._stdout_tee = io_wrap.Tee.pipe(*stdout_streams)
            self._stderr_tee = io_wrap.Tee.pipe(*stderr_streams)
            # Seems like the following actually isn't necessary on Windows
            # TODO(adrian): we may need to do the following if we use pipes instead of PTYs
            # because Python on Unix doesn't like writing UTF-8 to files
            # tell child python interpreters we accept utf-8
            # env['PYTHONIOENCODING'] = 'UTF-8'
        else:
            self._stdout_tee = io_wrap.Tee.pty(*stdout_streams)
            self._stderr_tee = io_wrap.Tee.pty(*stderr_streams)

        command = [program] + list(args)
        runner = util.find_runner(program)
        if runner:
            command = runner + command
        command = ' '.join(six.moves.shlex_quote(arg) for arg in command)
        self._stdout_stream.write_string(command + "\n\n")

        try:
            self.proc = subprocess.Popen(
                command,
                env=env,
                stdout=self._stdout_tee.tee_file,
                stderr=self._stderr_tee.tee_file,
                shell=True,
            )
            self._run.pid = self.proc.pid
        except (OSError, IOError):
            raise Exception('Could not find program: %s' % command)

        self._sync_etc()
145663
def main(argv):
    
    init()

    if OPTIONS.StdErrFileName.value:
        OPTIONS.stderr.value = open('wt', OPTIONS.StdErrFileName.value)

    asmlex.FILENAME = OPTIONS.inputFileName.value = argv[0]
    input_ = open(OPTIONS.inputFileName.value, 'rt').read()
    assemble(input_)
    generate_binary(OPTIONS.outputFileName.value, OPTIONS.output_file_type)
1353594
def init(self):
        
        import subprocess
        import fcntl
        
        width = str(self.image_dimensions[0])
        height = str(self.image_dimensions[1])
        
        comlist = self.executable.split() + [width, height, self.tmpfile] # e.g. "python3", "example_process1.py", etc.
        
        try:
            self.p = subprocess.Popen(comlist, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
        except Exception as e:
            print(self.pre, "Could not open external process.  Failed with '"+str(e)+"'")
            return
        
        self.reset()
1005546
def ls(serial=None):
    
    out, err = execute([
        'import os',
        'print(os.listdir())',
    ], serial)
    if err:
        raise IOError(clean_error(err))
    return ast.literal_eval(out.decode('utf-8'))
676092
def default(self, line):
        '''  '''
        try:
            encoding, count = self._ks.asm(line)
            machine_code = ""
            for opcode in encoding:
                machine_code += "\\x" + hexlify(pack("B", opcode)).decode()
            print("\"" + machine_code + "\"")
        except KsError as e:
            print("Error: %s" %e)
1163842
def open(self, name, mode="r", pwd=None):
        """"""
        if mode not in ("r", "U", "rU"):
            raise RuntimeError('open() requires mode "r", "U", or "rU"')
        if 'U' in mode:
            import warnings
            warnings.warn("'U' mode is deprecated",
                          DeprecationWarning, 2)
        if pwd and not isinstance(pwd, bytes):
            raise TypeError("pwd: expected bytes, got %s" % type(pwd))
        if not self.fp:
            raise RuntimeError(
                "Attempt to read ZIP archive that was already closed")

        # Make sure we have an info object
        if isinstance(name, ZipInfo):
            # 'name' is already an info object
            zinfo = name
        else:
            # Get info object for name
            zinfo = self.getinfo(name)

        self._fileRefCnt += 1

        zef_file = _SharedFile(
            self.fp, zinfo.header_offset, self._fpclose, self._lock)

        try:
            # Skip the file header:
            fheader = zef_file.read(sizeFileHeader)

            if len(fheader) != sizeFileHeader:
                raise BadZipFile("Truncated file header")

            fheader = struct.unpack(structFileHeader, fheader)
            # print(fheader)

            if fheader[_FH_SIGNATURE] != stringFileHeader:
                raise BadZipFile("Bad magic number for file header")

            # 注意：头部的文件长度可能会被修改
            len_fname = fheader[_FH_FILENAME_LENGTH]
            if len_fname > 256:
                # 自动修正文件名长度，但是，不能保证解压成功
                len_fname = len(zinfo.orig_filename)

            fname = zef_file.read(len_fname)

            if fheader[_FH_EXTRA_FIELD_LENGTH]:
                zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])

            # zinfo.flag_bits ^= zinfo.flag_bits % 2

            if zinfo.flag_bits & 0x20:
                # Zip 2.7: compressed patched data
                raise NotImplementedError(
                    "compressed patched data (flag bit 5)")

            if zinfo.flag_bits & 0x40:
                # strong encryption
                raise NotImplementedError("strong encryption (flag bit 6)")

            if zinfo.flag_bits & 0x800:
                # UTF-8 filename
                fname_str = fname.decode("utf-8")
            else:
                fname_str = fname.decode("cp437")

            if fname_str != zinfo.orig_filename:
                raise BadZipFile(
                    'File name in directory %r and header %r differ.'
                    % (zinfo.orig_filename, fname))

            return ZipExtFile(zef_file, mode, zinfo, None, True)
        except Exception as ignore:
            zef_file.close()
            raise
951733
def main(args):
    

    parser = argparse.ArgumentParser(usage="python -m premailer [options]")

    parser.add_argument(
        "-f",
        "--file",
        nargs="?",
        type=argparse.FileType("r"),
        help="Specifies the input file.  The default is stdin.",
        default=sys.stdin,
        dest="infile",
    )

    parser.add_argument(
        "-o",
        "--output",
        nargs="?",
        type=argparse.FileType("w"),
        help="Specifies the output file.  The default is stdout.",
        default=sys.stdout,
        dest="outfile",
    )

    parser.add_argument("--base-url", default=None, type=str, dest="base_url")

    parser.add_argument(
        "--remove-internal-links",
        default=True,
        help="Remove links that start with a '#' like anchors.",
        dest="preserve_internal_links",
    )

    parser.add_argument(
        "--exclude-pseudoclasses",
        default=False,
        help="Pseudo classes like p:last-child', p:first-child, etc",
        action="store_true",
        dest="exclude_pseudoclasses",
    )

    parser.add_argument(
        "--preserve-style-tags",
        default=False,
        help="Do not delete <style></style> tags from the html document.",
        action="store_true",
        dest="keep_style_tags",
    )

    parser.add_argument(
        "--remove-star-selectors",
        default=True,
        help="All wildcard selectors like '* {color: black}' will be removed.",
        action="store_false",
        dest="include_star_selectors",
    )

    parser.add_argument(
        "--remove-classes",
        default=False,
        help="Remove all class attributes from all elements",
        action="store_true",
        dest="remove_classes",
    )

    parser.add_argument(
        "--capitalize-float-margin",
        default=False,
        help="Capitalize float and margin properties for outlook.com compat.",
        action="store_true",
        dest="capitalize_float_margin",
    )

    parser.add_argument(
        "--strip-important",
        default=False,
        help="Remove '!important' for all css declarations.",
        action="store_true",
        dest="strip_important",
    )

    parser.add_argument(
        "--method",
        default="html",
        dest="method",
        help="The type of html to output. 'html' for HTML, 'xml' for XHTML.",
    )

    parser.add_argument(
        "--base-path",
        default=None,
        dest="base_path",
        help="The base path for all external stylsheets.",
    )

    parser.add_argument(
        "--external-style",
        action="append",
        dest="external_styles",
        help="The path to an external stylesheet to be loaded.",
    )

    parser.add_argument(
        "--css-text",
        action="append",
        dest="css_text",
        help="CSS text to be applied to the html.",
    )

    parser.add_argument(
        "--disable-basic-attributes",
        dest="disable_basic_attributes",
        help="Disable provided basic attributes (comma separated)",
        default=[],
    )

    parser.add_argument(
        "--disable-validation",
        default=False,
        action="store_true",
        dest="disable_validation",
        help="Disable CSSParser validation of attributes and values",
    )

    parser.add_argument(
        "--pretty",
        default=False,
        action="store_true",
        help="Pretty-print the outputted HTML.",
    )

    parser.add_argument(
        "--encoding", default="utf-8", help="Output encoding. The default is utf-8"
    )

    options = parser.parse_args(args)

    if options.disable_basic_attributes:
        options.disable_basic_attributes = options.disable_basic_attributes.split()

    html = options.infile.read()
    if hasattr(html, "decode"):  # Forgive me: Python 2 compatability
        html = html.decode("utf-8")

    p = Premailer(
        html=html,
        base_url=options.base_url,
        preserve_internal_links=options.preserve_internal_links,
        exclude_pseudoclasses=options.exclude_pseudoclasses,
        keep_style_tags=options.keep_style_tags,
        include_star_selectors=options.include_star_selectors,
        remove_classes=options.remove_classes,
        strip_important=options.strip_important,
        external_styles=options.external_styles,
        css_text=options.css_text,
        method=options.method,
        base_path=options.base_path,
        disable_basic_attributes=options.disable_basic_attributes,
        disable_validation=options.disable_validation,
    )
    options.outfile.write(
        p.transform(encoding=options.encoding, pretty_print=options.pretty)
    )
    return 0
768112
def main() -> None:
    
    logging.basicConfig(level=logging.DEBUG)
    parser = argparse.ArgumentParser()
    parser.add_argument("inputfile", nargs="?", help="Input file name")
    parser.add_argument(
        "--availability", nargs='*',
        help="File extensions to check availability for (use a '.' prefix, "
             "and use the special extension 'None' to check the fallback "
             "processor")
    parser.add_argument(
        "--plain", action="store_true",
        help="Keep it plain: minimize layout (e.g. of tables) and maximize "
             "the likelihood of source sentence flowing properly in the "
             "output (e.g. for natural language processing).")
    parser.add_argument(
        "--width", type=int, default=DEFAULT_WIDTH,
        help="Word wrapping width (default {})".format(DEFAULT_WIDTH))
    parser.add_argument(
        "--min-col-width", type=int, default=DEFAULT_MIN_COL_WIDTH,
        help="Minimum column width for tables (default {})".format(
            DEFAULT_MIN_COL_WIDTH))
    args = parser.parse_args()
    if args.availability:
        for ext in args.availability:
            if ext.lower() == 'none':
                ext = None
            available = is_text_extractor_available(ext)
            print("Extractor for extension {} present: {}".format(ext,
                                                                  available))
        return
    if not args.inputfile:
        parser.print_help(sys.stderr)
        return
    config = TextProcessingConfig(
        width=args.width,
        min_col_width=args.min_col_width,
        plain=args.plain,
    )
    result = document_to_text(filename=args.inputfile, config=config)
    if result is None:
        return
    else:
        print(result)
1315205
def main(argv=None):
    
    if not argv:
        argv = sys.argv[1:]

    parser = argparse.ArgumentParser(description=_HELP_TEXT)
    parser.add_argument('input', nargs='?', default=None)
    parser.add_argument('output', nargs='?', default=None)
    parser.add_argument('--version', action='version',
                        version='%(prog)s ' + get_version())
    args = parser.parse_args(argv)

    if not args.input:
        print("No file specified", file=sys.stderr)
        sys.exit(1)

    try:
        with open(args.input, 'r') as f:
            res = mangle(f.read())
            if not args.output:
                print(res, end='')
            else:
                with open(args.output, 'w') as o:
                    o.write(res)
    except Exception as ex:
        print("Error mangling {}: {!s}".format(args.input, ex),
              file=sys.stderr)
        sys.exit(1)
1304344
def file_or_stderr(filename, *, mode="a", encoding="utf-8"):
    
    if filename is not None:
        return open(filename, mode, encoding=encoding)

    @contextmanager
    def stderr_wrapper():
        yield sys.stderr

    return stderr_wrapper()
328825
def _open_text(fname, **kwargs):
    
    if PY3:
        kwargs.setdefault('encoding', ENCODING)
        kwargs.setdefault('errors', ENCODING_ERRS)
    return open(fname, "rt", **kwargs)
934382
def handel_default(self) -> None:
        
        raw_body = self._body
        body = cast(Optional[bytes], None)
        default_type = 2
        charset = self._charset or self._default_charset
        if raw_body is None:
            pass
        elif isinstance(raw_body, bytes):
            # body为bytes
            default_type = 2
            body = raw_body
        elif isinstance(raw_body, str):
            # body 为字符串
            default_type = 2
            body = encode_str(raw_body, charset)
        elif isinstance(raw_body, (list, dict)):
            # body 为json
            default_type = 3
            body = encode_str(json.dumps(raw_body, ensure_ascii=False), charset)
        elif isinstance(raw_body, RawIOBase):
            # body 为文件
            default_type = 1
            body = raw_body.read()
            raw_body.close()
        if "Content-Length" not in self._headers and \
                "Transfer-Encoding" not in self._headers \
                or self._headers["Transfer-Encoding"] != "chunked":
            if self.length is None:
                if body is not None:
                    self.length = len(body)
                else:
                    self.length = 0
            # 设置默认 Content-Length
            self.set("Content-Length", str(self.length))
        # print(body[0], body[1])
        if body is not None and body.startswith(encode_str("<", charset)):
            default_type = 4
        if "Content-Type" not in self._headers.keys():
            type_str = self.type
            if type_str is None:
                temp = DEFAULT_TYPE.get(default_type)
                if temp is not None:
                    if default_type != 1:
                        temp += "; charset=%s" % charset
                    type_str = temp
            if type_str is not None:
                # 设置默认 Content-Type
                self.set("Content-Type", type_str)
        self._body = body