String storage in Python Class includes newline character

和自甴很熟 提交于 2019-12-13 06:21:47

问题


I have an output class that looks like the following (somewhat redacted):

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

I'm reading in a list of domains from a file, and passing it via this class to the following:

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

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

Which in turn then reads:

def run(arguments, output):

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

For whatever reason this is printing newlines after each print. For example:

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

This should read:

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

I know I've made a mistake with my objects, or how I'm referencing them somewhere - but I'm struggling to see it. What am I not understanding? It seems silly to handle this in my TerminalOutput() function and I'd rather sort it as the domain is stored.

The file is being read in with:

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

Which is called in an argparse class using:

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)
)

回答1:


You are not showing us how you read the domains, but using:

for domain in domainFileDescriptor:
     domains.append(domain)

#or
domains=domainFileDescriptor.readlines()

will conserve the newline at the end of every line read from the file. You need to strip them:

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

The hint is the placement of the newline (right after the domain). Note: a file descriptor and handle is the same thing in this context.



来源:https://stackoverflow.com/questions/51980038/string-storage-in-python-class-includes-newline-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!