将字符串中的换行符从命令行传递到python脚本中

Ast*_*art 8 python bash getopt

我有一个脚本,我从命令行运行,我希望能够将字符串参数传递给.如在

script.py --string "thing1\nthing2"
Run Code Online (Sandbox Code Playgroud)

这样程序会将'\n'解释为新行.如果string="thing1\nthing2"我想得到

print string
Run Code Online (Sandbox Code Playgroud)

回来:

thing1
thing2
Run Code Online (Sandbox Code Playgroud)

而不是 thing1\nthing2

如果我只是将字符串"thing1 \nthing2"硬编码到脚本中,它会执行此操作,但如果它通过getopt作为命令行参数输入,则它无法识别它.我已经尝试了很多方法:在cl字符串中读取,r"%s" % arg在命令行上指定它的各种方法等,似乎没有任何工作.想法?这完全不可能吗?

Tes*_*ler 10

从Bash中的/sf/answers/344288941/,您可以使用:

script.py --string $'thing1\nthing2'
Run Code Online (Sandbox Code Playgroud)

例如

$ python test.py $'1\n2'
1
2
Run Code Online (Sandbox Code Playgroud)

但那是Bash特有的语法.

  • 请注意,单引号很重要. (4认同)

Dav*_*ers 7

这实际上是一个shell问题,因为shell会执行所有命令解析。Python不在乎发生了什么,只在exec系统调用中得到了结果。如果您使用的是bash,则不会在双引号之间进行某种形式的转义。如果你想要的东西一样\n\t\xnn进行转义,下面的语法是bash的扩展:

python test.py $'thing1\nthing2'
Run Code Online (Sandbox Code Playgroud)

您也可以:

python test.py "thing1
thing2"
Run Code Online (Sandbox Code Playgroud)

如果您有兴趣,这里有一些有关bash报价的更多信息。即使您不使用bash,它仍然是不错的阅读方法:

http://mywiki.wooledge.org/语录


biw*_*biw -2

这个比较简单,我很惊讶没有人说过。

在你的Python脚本中只需编写以下代码

print string.replace("\\n", "\n")
Run Code Online (Sandbox Code Playgroud)

您将得到打印有新行的字符串,而不是 \n。

  • 这实际上更像是一种补偿错误参数数据的黑客行为。 (4认同)