【问题标题】:String storage in Python Class includes newline characterPython 类中的字符串存储包括换行符
【发布时间】:2018-08-23 07:01:57
【问题描述】:

我有一个如下所示的输出类(有些编辑):

from colorclass import Color
from colorclass import disable_all_colors, enable_all_colors, is_enabled
from time import localtime, strftime
from ApplicationFiles.lib.core.__version__ import __version__
from enum import IntEnum


class OutputHelper(object):
    def __init__(self, arguments, app):

        if arguments.nocolor:
            disable_all_colors()

        self.domain = "undefined"
        self.severity_print = arguments.severity
        self.verbose = arguments.verbose
        self.silent = arguments.silent
        self.seperator = "=============================================="
        self.modules_count = app.modules_count()

    # this is here to allow easier redirection of output to other
    # interfaces later on in the project
    def write(self, severity, message):
        self.terminal(severity, message)

    def terminal(self, severity, message):
        if severity == 0 and not self.verbose:
            return

        if severity < self.severity_print:
            return

        formatting = {
           0: Color('{autoblue}[VERBOSE]{/autoblue}')
        }

        leader = formatting.get(severity, '[#]')

        format_args = {
           'time': strftime("%H:%M:%S", localtime()),
           'domain': self.domain,
           'leader': leader,
           'message': message,
        }

        template = '[{time}] [{domain}] {leader} {message}'
        print(template.format(**format_args))


class Level(IntEnum):
    VERBOSE = 0

我正在从文件中读取域列表,并通过此类将其传递给以下内容:

for domain in arguments.domain_list:
    domains.append(domain)

for domain in domains:
    output.domain = domain
    app.modules['example_module'].run(arguments, output)

然后依次显示:

def run(arguments, output):

    output.write(Level.VERBOSE, 'TEST DOMAIN')

无论出于何种原因,这都会在每次打印后打印换行符。例如:

1 modules loaded
==============================================
[16:57:25] [testone.com
] [VERBOSE] TEST DOMAIN
[16:57:25] [testtwo.com
] [VERBOSE] TEST DOMAIN
[16:57:25] [testthree.com
] [VERBOSE] TEST DOMAIN

这应该是:

1 modules loaded
==============================================
[16:57:25] [testone.com] [VERBOSE] TEST DOMAIN
[16:57:25] [testtwo.com] [VERBOSE] TEST DOMAIN
[16:57:25] [testthree.com] [VERBOSE] TEST DOMAIN

我知道我的对象出错了,或者我在某处引用它们的方式有误 - 但我很难看到它。我不明白什么?在我的 TerminalOutput() 函数中处理这个似乎很愚蠢,我宁愿在存储域时对其进行排序。

正在读入文件:

def readable_file(parser, arg):
    if not os.path.exists(arg):
        parser.error("The file %s does not exist!" % arg)
    else:
        return open(arg, 'r')  # return an open file handle

在 argparse 类中使用:

domains.add_argument(
    '-dL', dest='domain_list', required=False,
    help='Specify a list of target domain names.',
    metavar="FILE",
    type=lambda x: CliFileHelper.readable_file(parser, x)
)

【问题讨论】:

  • 错误可能来自文件解析,你.strip()空格/换行符吗?
  • @PRMoureu 可能是这样。我添加了更多信息,包括我在文件中的阅读方式。
  • 检查domain 中的format_args 是否有换行符
  • @MohitSolanki 这不是一个真正的解决方案,因为从那时起,随着域在模块中使用,这将重新出现。对此的修复不应基于输出本身。
  • 只是一个与我的答案无关的注释 - 查看关于如何处理不存在的文件的鸭子打字。我认为 Python 的常见做法是假设它存在,如果你想处理它,就捕获异常。

标签: python string terminal


【解决方案1】:

您没有向我们展示您如何阅读域,而是使用:

for domain in domainFileDescriptor:
     domains.append(domain)

#or
domains=domainFileDescriptor.readlines()

将在从文件读取的每一行末尾保留换行符。您需要剥离它们:

for domain in domainFileDescriptor:
     domains.append(domain.strip())

提示是换行符的位置(域之后)。注意:在这种情况下,文件描述符和句柄是一样的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-15
    • 2018-10-01
    • 1970-01-01
    相关资源
    最近更新 更多