bash 从命令行将字符串中的换行符传递到 python 脚本中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26517674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing newline within string into a python script from the command line
提问by Astro_Dart
I have a script that I run from the command line which I would like to be able to pass string arguments into. As in
我有一个从命令行运行的脚本,我希望能够将字符串参数传递到其中。如
script.py --string "thing1\nthing2"
such that the program would interpret the '\n' as a new line. If string="thing1\nthing2"
I want to get
这样程序就会将 '\n' 解释为一个新行。如果string="thing1\nthing2"
我想得到
print string
to return:
返回:
thing1
thing2
rather than thing1\nthing2
而不是 thing1\nthing2
If I simply hard-code the string "thing1\nthing2" into the script, it does this, but if it's entered as a command line argument via getopt, it doesn't recognize it. I have tried a number of approaches to this: reading in the cl string as r"%s" % arg
, various ways of specifying it on the commandline, etc, and nothing seems to work. Ideas? Is this completely impossible?
如果我只是将字符串 "thing1\nthing2" 硬编码到脚本中,它会这样做,但是如果通过 getopt 作为命令行参数输入它,它就无法识别它。我为此尝试了多种方法:读取 cl 字符串 as r"%s" % arg
,在命令行上指定它的各种方法等,但似乎没有任何效果。想法?这是完全不可能的吗?
采纳答案by biw
This one is relatively simple and I am surprised no one has said it.
这个比较简单,我很惊讶没有人说过。
In your python script just write the following code
在你的python脚本中只需编写以下代码
print string.replace("\n", "\n")
and you will get the string printed with the new line and not the \n.
并且您将使用新行而不是 \n 打印字符串。
回答by TessellatingHeckler
From https://stackoverflow.com/a/4918413/478656in Bash, you can use:
从https://stackoverflow.com/a/4918413/478656在 Bash 中,您可以使用:
script.py --string $'thing1\nthing2'
e.g.
例如
$ python test.py $'1\n2'
1
2
But that's Bash-specific syntax.
但这是 Bash 特定的语法。
回答by David Sanders
This is really a shell question since the shell does all the command parsing. Python doesn't care what's happening with that and only gets what comes through in the exec
system call. If you're using bash, it doesn't do certain kinds of escaping between double quotes. If you want things like \n
, \t
, or \xnn
to be escaped, the following syntax is a bash extension:
这确实是一个 shell 问题,因为 shell 会执行所有命令解析。Python 不关心发生了什么,只获取exec
系统调用中发生的事情。如果您使用 bash,它不会在双引号之间进行某些类型的转义。如果你想要的东西一样\n
,\t
或\xnn
进行转义,下面的语法是bash的扩展:
python test.py $'thing1\nthing2'
Note that the above example uses single quotes and not double quotes. That's important. Using double quotes causes different rules to apply. You can also do:
请注意,上面的示例使用单引号而不是双引号。这很重要。使用双引号会导致应用不同的规则。你也可以这样做:
python test.py "thing1
thing2"
Here's some more info on bash quoting if you're interested. Even if you're not using bash, it's still good reading:
如果您有兴趣,这里有一些关于 bash 引用的更多信息。即使你不使用 bash,它仍然是很好的阅读: