Search code examples
pythonpython-3.xoptparse

Can't break a line with string in optparse


I am trying to break a line with \n with optparse. Example: line1 \n line2 But when I type \n it doesn't break it just prints it as line1 \n line2, instead of doing a break. Here is my code:

import optparse
import sys

def main():
    progparse = optparse.OptionParser("usage " + "--message <text here>")
    progparse.add_option("--message", dest="msg_txt", type="string", help="Type the message you want to send")

    msg_txt = ""

    if (options.msg_txt == None):
        print(progparse.usage)
        sys.exit()

    print(options.msg_txt)

if __name__ == '__main__':
    main()

If I just do a simple print statment with \n then it will break the line, why doesn't it do it when using optparse?


Solution

  • option1, use real new line in your input:

    $ python3 test.py --message "line1
    > line2
    > line3"
    line1
    line2
    line3
    

    option2, eval \n as real new line with ast.literal_eval:

    print(ast.literal_eval('"' + options.msg_txt + '"'))
    

    note this may raise an exception for ill-formed input.