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

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


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

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

e.g.

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

But that's Bash-specific syntax.


This is really a shell question since the shell does all the command parsing. Python doesn't care what's happening with that and only gets what comes through in the exec system call. If you're using bash, it doesn't do certain kinds of escaping between double quotes. If you want things like \n, \t, or \xnn to be escaped, the following syntax is a bash extension:

python test.py $'thing1\nthing2'

Note that the above example uses single quotes and not double quotes. That's important. Using double quotes causes different rules to apply. You can also do:

python test.py "thing1thing2"

Here's some more info on bash quoting if you're interested. Even if you're not using bash, it's still good reading:

http://mywiki.wooledge.org/Quotes


This one is relatively simple and I am surprised no one has said it.

In your python script just write the following code

print string.replace("\\n", "\n")

and you will get the string printed with the new line and not the \n.