0

I want to enter newline in option such as --opt hello\nworld\n

Here is code snippet:

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument('--embed', dest='embed', default=None, help='embed info')
    return parser.parse_args()
if __name__ == '__main__':
    args = parse_args()
    print args.embed # It shows: hellonworldn

I execute like below:

python test.py --embed hello\nworld\n

But it always failed ans shows no newline symbols:

hellonworldn

I also execute like below:

python test.py --embed "hello\nworld\n"

But it still failed ans print without newline:

hello\nworld\n

How to reserve the newline symbol and make the output like below?

hello
world
code_worker
  • 384
  • 3
  • 16

1 Answers1

1

I can't quite reproduce the problem:

C:\Users\pi\Desktop>C:\Anaconda3\python test.py --embed hello\nworld\n
hello\nworld\n

So the string is read correctly, interpreting the backslashes as literal backslashes. If you want them to be parsed, use

print args.embed.decode("string_escape")

In Python 3, it would look a little different (see Process escape sequences in a string in Python)

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Aside from the official [Python tutorial](http://docs.python.org/3/tutorial/index.html), and the [`codecs` module](http://docs.python.org/3/library/codecs.html), there is the classic Joel blog post https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/ (from 2003, still relevant). Also very good: Anything by Ned Batchelder: https://nedbatchelder.com/text/unipain.html – Tim Pietzcker Jul 25 '18 at 09:13
  • By the way, why Python 2.7? Python 3 has been out for ages, Python 2 has only received bug fixes since 2010... – Tim Pietzcker Jul 25 '18 at 09:15
  • Because I tried program myself in Python2.7. I'll do my best to transfer to python3 – code_worker Jul 26 '18 at 11:00