为什么`\n`不能在Python中工作

Rah*_*til 5 bash shell cmd

我正在尝试以下示例:

python -c "import sys; print sys.argv[1]" "test\ntest"

输出:

test\ntest
Run Code Online (Sandbox Code Playgroud)

但我想要跟随

test 
test
Run Code Online (Sandbox Code Playgroud)

更新1#由于@devnull建议可以解决问题,如果用户自己通过了$但是python应该如何解决这个问题?

我试过了 :

python -c "import sys; print '$' + sys.argv[1]" 'test\ntest'
Run Code Online (Sandbox Code Playgroud)

但输出:

$test\ntest
Run Code Online (Sandbox Code Playgroud)

sko*_*oll 4

正如 deed02392 提到的,shell 按字面意思发送字符,因此 python 在内部“转义”反斜杠。要明白我的意思,请尝试

python -c "import sys; print repr(sys.argv[1])" "test\ntest"
'test\\ntest'
Run Code Online (Sandbox Code Playgroud)

要解决此问题,请执行以下操作:

python -c "import sys; print sys.argv[1].decode('string_escape')" "test\ntest"
test
test
Run Code Online (Sandbox Code Playgroud)