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

2019-09-21 18:52发布

This question already has an answer here:

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

标签: python shell
3条回答
我命由我不由天
2楼-- · 2019-09-21 19:16
'\\\\n' == '\\' + '\\' + 'n'

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

查看更多
仙女界的扛把子
3楼-- · 2019-09-21 19:30

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.

查看更多
Deceive 欺骗
4楼-- · 2019-09-21 19:35

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

查看更多
登录 后发表回答