Passing a new line inside a line in a python script from the command line

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

script.py --string "thing1\nthing2" 

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

 print string 

:

 thing1 thing2 

not thing1\nthing2

If I just hardcode the string "thing1 \ nthing2" in the script, it does it, but if it is entered as a command line argument via getopt, it does not recognize it. I tried a number of approaches to this: reading in the cl line as r"%s" % arg , various ways to specify it on the command line, etc., and nothing works. Ideas? Is it absolutely impossible?

+7
python bash getopt
source share
3 answers

It is quite simple, and I am surprised that no one has said this.

In your python script just write the following code

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

and you will get a line printed with a new line, not \ n.

-3
source share

From https://stackoverflow.com/a/3129608/2128328 of Bash.site/questions/819055 / ... in Bash you can use:

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

eg.

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

But this Bash is a specific syntax.

+8
source share

This is really a shell issue, since the shell does all the parsing of the command. Python does not care about what happens with this, and only gets what happens in the exec system call. If you use bash, it does not perform certain types of escaping between double quotes. If you want things like \n , \t or \xnn to be escaped, the following syntax is the bash extension:

 python test.py $'thing1\nthing2' 

You can also do:

 python test.py "thing1 thing2" 

Here's some more info on bash quoting if you're interested. Even if you are not using bash, this is still a good read:

http://mywiki.wooledge.org/Quotes

+1
source share

All Articles