'\\n' is treated as '\\' and '

2019-09-21 19:03发布

问题:

This question already has an answer here:

  • error: stray '\' in program in macro definition 1 answer

The following python code

env.Command(versionFile, allSrcs + [".git/index", "SConstruct"],
        'echo "#define ZSIM_BUILDDATE \\""`date`\\""\\\\n#define ZSIM_BUILDVERSION \\""`python misc/gitver.py`\\""" >>' + versionFile)

produces an output like this

$ cat build/opt/version.h
#define ZSIM_BUILDDATE "Sat Apr 19 13:31:41 CET 2014"\n#define ZSIM_BUILDVERSION "master:10:a8c417b:2fc 3+ 2- d5cec7e7"

As you can see it doesn't understand that '\n' means new line+carriage return. Instead it just print '\' and 'n'.

How can I fix that?

P.S: This question is a follow-up for this one. the previous post was general and didn't pinpoint to the problem. Also I use scons for build. any help would be appreciated. thank you

回答1:

You want echo -e ... so that echo understands that \n is an escape sequence for newline



回答2:

That's not actually either a python or a C++ question as you are complaining about the behavior of shell quoting (some shells allow escape codes like \n in arguments when you use something like echo -e though).

So if you want to get a newline in, try producing it in Python already (newline inside of quoted strings will make it into the argument of echo) rather than producing some escape sequence that the shell will not further process.



回答3:

'\\\\n' == '\\' + '\\' + 'n'

You're escaping 2 backslashes, so in the next interpretation it comes down to \\n. So just replace \\\\n with \\n



标签: python shell