python类linesep()的实例源码

mailbox.py 文件源码 项目:hostapd-mana 作者: adde88 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def get_string(self, key):
        """Return a string representation or raise a KeyError."""
        start, stop = self._lookup(key)
        self._file.seek(start)
        self._file.readline()   # Skip '1,' line specifying labels.
        original_headers = StringIO.StringIO()
        while True:
            line = self._file.readline()
            if line == '*** EOOH ***' + os.linesep or line == '':
                break
            original_headers.write(line.replace(os.linesep, '\n'))
        while True:
            line = self._file.readline()
            if line == os.linesep or line == '':
                break
        return original_headers.getvalue() + \
               self._file.read(stop - self._file.tell()).replace(os.linesep,
                                                                 '\n')
quiz.py 文件源码 项目:idem 作者: mazerty 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def hard(args):
    ref = collections.defaultdict(list)

    with open(args.ref, "rb") as f:
        b = f.read(1)
        i = 0
        while b:
            ref[b].append(i)
            i = i + 1
            b = f.read(1)

    if len(ref) < 256:
        raise Exception

    output = []

    with open(args.input, "rb") as f:
        b = f.read(1)
        while b:
            output.append(ref[b][random.randrange(len(ref[b]))])
            b = f.read(1)

    with open(args.output, "w") as f:
        for item in output:
            f.write(str(item) + os.linesep)
StreamHandler.py 文件源码 项目:packet_analysis 作者: tanjiti 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __parse_data(self, proto_parse_class, data, file_hd):
        """

        Args:
            proto_parse_class:
            data:
            file_hd:

        Returns:

        """

        proto_parse_ob = proto_parse_class(data)
        data_yield = proto_parse_ob.parse_data(sep="\x00")
        for d in data_yield:
            if d:
                if file_hd:
                    file_hd.write("%r%s" % (d, os.linesep))
                if self.std_output_enable:
                    if not isinstance(d, dict):
                        d = d.toDict()
                    print json.dumps(d, indent=4)
dynamo0p3.py 文件源码 项目:PSyclone 作者: stfc 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __str__(self):
        res = "DynArgDescriptor03 object" + os.linesep
        res += "  argument_type[0]='{0}'".format(self._type)
        if self._vector_size > 1:
            res += "*"+str(self._vector_size)
        res += os.linesep
        res += "  access_descriptor[1]='{0}'".format(self._access_descriptor) \
               + os.linesep
        if self._type == "gh_field":
            res += "  function_space[2]='{0}'".format(self._function_space1) \
                   + os.linesep
        elif self._type in VALID_OPERATOR_NAMES:
            res += "  function_space_to[2]='{0}'".\
                   format(self._function_space1) + os.linesep
            res += "  function_space_from[3]='{0}'".\
                   format(self._function_space2) + os.linesep
        elif self._type in VALID_SCALAR_NAMES:
            pass  # we have nothing to add if we're a scalar
        else:  # we should never get to here
            raise ParseError("Internal error in DynArgDescriptor03.__str__")
        return res
cherry_picker.py 文件源码 项目:core-workflow 作者: python 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def amend_commit_message(self, cherry_pick_branch):
        """ prefix the commit message with (X.Y) """

        commit_prefix = ""
        if self.prefix_commit:
            commit_prefix = f"[{get_base_branch(cherry_pick_branch)}] "
        updated_commit_message = f"{commit_prefix}{self.get_commit_message(self.commit_sha1)}{os.linesep}(cherry picked from commit {self.commit_sha1})"
        updated_commit_message = updated_commit_message.replace('#', 'GH-')
        if self.dry_run:
            click.echo(f"  dry-run: git commit --amend -m '{updated_commit_message}'")
        else:
            try:
                subprocess.check_output(["git", "commit", "--amend", "-m",
                                         updated_commit_message],
                                         stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as cpe:
                click.echo("Failed to amend the commit message  \u2639")
                click.echo(cpe.output)
        return updated_commit_message
convert_model.py 文件源码 项目:Generative-ConvACs 作者: HUJI-Deep 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def convert_and_parse_xml(src_model_fname):
    dst_model_fname = os.path.basename(src_model_fname).split('.')[0] + '.xml.mdl'
    with open(dst_model_fname, 'wb') as wfile:
        wfile.write('<MODEL>\n')
        with open(src_model_fname, 'rb') as rfile:
            for line in rfile.readlines():
                newline = line
                if '<CNT>' in line:
                    newline = line.strip() + '</CNT>'
                elif '<MEAN>' in line:
                    newline = line.strip() + '</MEAN>'

                elif pn_re.findall(line):
                    newline = pn_re.sub(r'@ \2 \3 \4 \5 @',line)

                wfile.write(newline.strip() + os.linesep)
            wfile.write('</MODEL>\n')

    xmldoc = minidom.parse(dst_model_fname)
    os.remove(dst_model_fname)
    return xmldoc
display.py 文件源码 项目:eyeD3 作者: nicfit 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def start(self, args, config):
        super(DisplayPlugin, self).start(args, config)

        if args.pattern_help:
            self.__print_pattern_help()
            return

        if not _have_grako:
            console.printError(u"Unknown module 'grako'" + os.linesep +
                               u"Please install grako! " +
                               u"E.g. $ pip install grako")
            self.__return_code = 2
            return

        if args.pattern_string is not None:
            self.__pattern = Pattern(args.pattern_string)
        if args.pattern_file is not None:
            pfile = open(args.pattern_file, "r")
            self.__pattern = Pattern(''.join(pfile.read().splitlines()))
            pfile.close()
        self.__output_ending = "" if args.no_newline else os.linesep
display.py 文件源码 项目:eyeD3 作者: nicfit 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def __print_pattern_help(self):
        # FIXME: Force some order
        print(console.formatText("ID3 Tags:", b=True))
        self.__print_complex_pattern_help(TagPattern)
        print(os.linesep)

        print(console.formatText("Functions:", b=True))
        self.__print_complex_pattern_help(FunctionPattern)
        print(os.linesep)

        print(console.formatText("Special characters:", b=True))
        print(console.formatText("\tescape seq.   character"))
        for i in range(len(TextPattern.SPECIAL_CHARACTERS)):
            print(("\t\\%s" + (" " * 12) + "%s") %
                  (TextPattern.SPECIAL_CHARACTERS[i],
                   TextPattern.SPECIAL_CHARACTERS_DESCRIPTIONS[i]))
util.py 文件源码 项目:TCP-IP 作者: JackZ0 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _wrap_lines(msg):
    """Format lines nicely to 80 chars.

    :param str msg: Original message

    :returns: Formatted message respecting newlines in message
    :rtype: str

    """
    lines = msg.splitlines()
    fixed_l = []

    for line in lines:
        fixed_l.append(textwrap.fill(
            line,
            80,
            break_long_words=False,
            break_on_hyphens=False))

    return os.linesep.join(fixed_l)
main.py 文件源码 项目:TCP-IP 作者: JackZ0 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
def _ask_user_to_confirm_new_names(config, new_domains, certname, old_domains):
    """Ask user to confirm update cert certname to contain new_domains.
    """
    if config.renew_with_new_domains:
        return

    msg = ("You are updating certificate {0} to include domains: {1}{br}{br}"
           "It previously included domains: {2}{br}{br}"
           "Did you intend to make this change?".format(
               certname,
               ", ".join(new_domains),
               ", ".join(old_domains),
               br=os.linesep))
    obj = zope.component.getUtility(interfaces.IDisplay)
    if not obj.yesno(msg, "Update cert", "Cancel", default=True):
        raise errors.ConfigurationError("Specified mismatched cert name and domains.")
configurator_test.py 文件源码 项目:TCP-IP 作者: JackZ0 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_get_version(self, mock_script):
        mock_script.return_value = (
            "Server Version: Apache/2.4.2 (Debian)", "")
        self.assertEqual(self.config.get_version(), (2, 4, 2))

        mock_script.return_value = (
            "Server Version: Apache/2 (Linux)", "")
        self.assertEqual(self.config.get_version(), (2,))

        mock_script.return_value = (
            "Server Version: Apache (Debian)", "")
        self.assertRaises(errors.PluginError, self.config.get_version)

        mock_script.return_value = (
            "Server Version: Apache/2.3{0} Apache/2.4.7".format(
                os.linesep), "")
        self.assertRaises(errors.PluginError, self.config.get_version)

        mock_script.side_effect = errors.SubprocessError("Can't find program")
        self.assertRaises(errors.PluginError, self.config.get_version)
install_whl.py 文件源码 项目:bpy_lambda 作者: bcongdon 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def update_init_file(version: tuple):
    import os
    import re

    print('Updating __init__.py to have the correct version.')
    version_line_re = re.compile(r'^\s+[\'"]version[\'"]: (\([0-9,]+\)),')

    with open('__init__.py', 'r') as infile, \
         open('__init__.py~whl~installer~', 'w') as outfile:

        for line in infile:
            if version_line_re.match(line):
                outfile.write("    'version': %s,%s" % (version, os.linesep))
            else:
                outfile.write(line)

    os.unlink('__init__.py')
    os.rename('__init__.py~whl~installer~', '__init__.py')
base.py 文件源码 项目:dask-ml 作者: dask 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def _copy_partial_doc(cls):
    for base in cls.mro():
        if base.__module__.startswith('sklearn'):
            break
    lines = base.__doc__.split(os.linesep)
    header, rest = lines[0], lines[1:]

    insert = """

    This class wraps scikit-learn's {classname}. When a dask-array is passed
    to our ``fit`` method, the array is passed block-wise to the scikit-learn
    class' ``partial_fit`` method. This will allow you to fit the estimator
    on larger-than memory datasets sequentially (block-wise), but without an
    parallelism, or any ability to distribute across a cluster.""".format(
        classname=base.__name__)

    doc = '\n'.join([header + insert] + rest)

    cls.__doc__ = doc
    return cls
FunctionCommon.py 文件源码 项目:PhonePerformanceMeasure 作者: KyleCe 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def replace_line_in_file(f, start_exp, to_replace):
    lines = read_lines_of_file(f)
    for i in range(len(lines)):
        if lines[i].startswith(start_exp):
            lines[i] = to_replace + os.linesep
    write_lines_into_file(Res.project_path + f, lines)
editor.py 文件源码 项目:txt2evernote 作者: Xunius 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def ENMLtoText(contentENML):
        soup = BeautifulSoup(contentENML.decode('utf-8'))

        for section in soup.select('li > p'):
            section.replace_with( section.contents[0] )

        for section in soup.select('li > br'):
            if section.next_sibling:
                next_sibling = section.next_sibling.next_sibling
                if next_sibling:
                    if next_sibling.find('li'):
                        section.extract()
                else:
                    section.extract()

        Editor.checklistInENMLtoSoup(soup)

        for section in soup.findAll('en-todo', checked='true'):
            section.replace_with('[x]')

        for section in soup.findAll('en-todo'):
            section.replace_with('[ ]')

        content = html2text.html2text(str(soup).decode('utf-8'), '', 0)
        content = re.sub(r' *\n', os.linesep, content)

        return content.encode('utf-8')
__init__.py 文件源码 项目:python- 作者: secondtonone1 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def parseopts(args):
    parser = create_main_parser()

    # Note: parser calls disable_interspersed_args(), so the result of this
    # call is to split the initial args into the general options before the
    # subcommand and everything else.
    # For example:
    #  args: ['--timeout=5', 'install', '--user', 'INITools']
    #  general_options: ['--timeout==5']
    #  args_else: ['install', '--user', 'INITools']
    general_options, args_else = parser.parse_args(args)

    # --version
    if general_options.version:
        sys.stdout.write(parser.version)
        sys.stdout.write(os.linesep)
        sys.exit()

    # pip || pip help -> print_help()
    if not args_else or (args_else[0] == 'help' and len(args_else) == 1):
        parser.print_help()
        sys.exit()

    # the subcommand name
    cmd_name = args_else[0]

    if cmd_name not in commands_dict:
        guess = get_similar_commands(cmd_name)

        msg = ['unknown command "%s"' % cmd_name]
        if guess:
            msg.append('maybe you meant "%s"' % guess)

        raise CommandError(' - '.join(msg))

    # all the args without the subcommand
    cmd_args = args[:]
    cmd_args.remove(cmd_name)

    return cmd_name, cmd_args
__init__.py 文件源码 项目:python- 作者: secondtonone1 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def main(args=None):
    if args is None:
        args = sys.argv[1:]

    # Configure our deprecation warnings to be sent through loggers
    deprecation.install_warning_logger()

    autocomplete()

    try:
        cmd_name, cmd_args = parseopts(args)
    except PipError as exc:
        sys.stderr.write("ERROR: %s" % exc)
        sys.stderr.write(os.linesep)
        sys.exit(1)

    # Needed for locale.getpreferredencoding(False) to work
    # in pip.utils.encoding.auto_decode
    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error as e:
        # setlocale can apparently crash if locale are uninitialized
        logger.debug("Ignoring error %s when setting locale", e)
    command = commands_dict[cmd_name](isolated=check_isolated(cmd_args))
    return command.main(cmd_args)


# ###########################################################
# # Writing freeze files
__init__.py 文件源码 项目:my-first-blog 作者: AnkurBegining 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def parseopts(args):
    parser = create_main_parser()

    # Note: parser calls disable_interspersed_args(), so the result of this
    # call is to split the initial args into the general options before the
    # subcommand and everything else.
    # For example:
    #  args: ['--timeout=5', 'install', '--user', 'INITools']
    #  general_options: ['--timeout==5']
    #  args_else: ['install', '--user', 'INITools']
    general_options, args_else = parser.parse_args(args)

    # --version
    if general_options.version:
        sys.stdout.write(parser.version)
        sys.stdout.write(os.linesep)
        sys.exit()

    # pip || pip help -> print_help()
    if not args_else or (args_else[0] == 'help' and len(args_else) == 1):
        parser.print_help()
        sys.exit()

    # the subcommand name
    cmd_name = args_else[0]

    if cmd_name not in commands_dict:
        guess = get_similar_commands(cmd_name)

        msg = ['unknown command "%s"' % cmd_name]
        if guess:
            msg.append('maybe you meant "%s"' % guess)

        raise CommandError(' - '.join(msg))

    # all the args without the subcommand
    cmd_args = args[:]
    cmd_args.remove(cmd_name)

    return cmd_name, cmd_args
__init__.py 文件源码 项目:my-first-blog 作者: AnkurBegining 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def main(args=None):
    if args is None:
        args = sys.argv[1:]

    # Configure our deprecation warnings to be sent through loggers
    deprecation.install_warning_logger()

    autocomplete()

    try:
        cmd_name, cmd_args = parseopts(args)
    except PipError as exc:
        sys.stderr.write("ERROR: %s" % exc)
        sys.stderr.write(os.linesep)
        sys.exit(1)

    # Needed for locale.getpreferredencoding(False) to work
    # in pip.utils.encoding.auto_decode
    try:
        locale.setlocale(locale.LC_ALL, '')
    except locale.Error as e:
        # setlocale can apparently crash if locale are uninitialized
        logger.debug("Ignoring error %s when setting locale", e)
    command = commands_dict[cmd_name](isolated=check_isolated(cmd_args))
    return command.main(cmd_args)


# ###########################################################
# # Writing freeze files
setup.py 文件源码 项目:BioDownloader 作者: biomadeira 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def gather_dependencies():
    import os
    with open('requirements.txt', 'r') as f_in:
        return [l for l in f_in.read().rsplit(os.linesep) 
                if l and not l.startswith("#")]


问题


面经


文章

微信
公众号

扫码关注公众号