1

In Python, using argparse, is there any way to parse text containing a newline character given as a parameter?

I have this script:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse

parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('text', help='some text with newline')

args = parser.parse_args(["line1\nline2"])

print(args.text)

which prints as expected:

line1
line2

but if I give the argument at the command-line (after changing to args = parser.parse_args() in the script above) it's not doing the same. For example:

$ ./newline2argparse.py "line1\nline2"
line1\nline2

Any ideas on this?

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
PedroA
  • 1,803
  • 4
  • 27
  • 50
  • Your shell doesn't interpret `\n` as a line break. Is that bash you're using? – Aran-Fey Jun 01 '18 at 11:08
  • `which $SHELL` prints `/bin/bash`. I'm on a Mac OS. But there should be a way to deal with this within the python script? – PedroA Jun 01 '18 at 11:09
  • 1
    According to [this answer](https://stackoverflow.com/a/25269126/1222951) you can use `./newline2argparse.py $'line1\nline2'`. – Aran-Fey Jun 01 '18 at 11:13

2 Answers2

1

Your \n is taken as \ followed by n and not interpreted as it should. Use a command like echo or printf to correctly interpret it. This should work on almost any shell (sh, bash, zsh, etc).

$ ./newline2argparse.py "$(echo -en 'line1\nline2')"
$ ./newline2argparse.py "$(printf 'line1\nline2')"
$ ./newline2argparse.py `printf "line1\nline2"`

There are plenty of alternatives.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • 1
    accepted this answer because it seems more "universal" across shells but @Barmar answer's is more concise for `bash`. – PedroA Jun 01 '18 at 11:24
1

If you want escape sequences to be processed in a shell string, surround it with $''

./newline2argparse.py $'line1\nline2'

Note that this is a bash extension, it may not be supported by all other shells.

Barmar
  • 741,623
  • 53
  • 500
  • 612