Python – Passing newline within string into a python script from the command line

bashgetoptpython

I have a script that I run from the command line which I would like to be able to pass string arguments into. As in

script.py --string "thing1\nthing2"

such that the program would interpret the '\n' as a new line. If string="thing1\nthing2" I want to get

print string

to return:

thing1
thing2

rather than thing1\nthing2

If I simply hard-code the string "thing1\nthing2" into the script, it does this, but if it's entered as a command line argument via getopt, it doesn't recognize it. I have tried a number of approaches to this: reading in the cl string as r"%s" % arg, various ways of specifying it on the commandline, etc, and nothing seems to work. Ideas? Is this completely impossible?

Best Solution

From https://stackoverflow.com/a/4918413/478656 in Bash, you can use:

script.py --string $'thing1\nthing2'

e.g.

$ python test.py $'1\n2'
1
2

But that's Bash-specific syntax.