Python sys.argv 保留 ' ' 或 ""

10

终端:

python test.py blah='blah'

在test.py中

print sys.argv
['test.py', 'blah=blah'] <------------ 

如何保留blah参数的“”或''?
有没有一种方法可以知道参数是否用“”或''包装?


4
这不是由Python控制的... 这是你的* shell *在将其传递给Python之前删除引号。 - Martijn Pieters
2
是 shell “剥离” 引号;请使用 python test.py "blah='blah'" - Gumbo
1
这似乎是一个 XY 问题。你为什么需要这些引号? - dawg
如果您的应用程序需要接受自由格式文本而不是从命令行参数中获取的符号化数据,那么从标准输入读取文本可能会更容易。 - millimoose
请提及您使用的操作系统或shell。 - Bleeding Fingers
2个回答

13
你的shell在调用Python之前会移除引号,这不是Python能够控制的。
添加更多引号:
python test.py "blah='blah'"

也可以放置在参数的任何位置:

python test.py blah="'blah'"

或者您可以使用反斜杠转义:

python test.py blah=\'blah\'

为了保存它们,这取决于你用来运行命令的确切shell。

bash示例:

$ cat test.py 
import sys
print sys.argv
$ python test.py blah='blah'
['test.py', 'blah=blah']
$ python test.py "blah='blah'"
['test.py', "blah='blah'"]
$ python test.py blah="'blah'"
['test.py', "blah='blah'"]
$ python test.py blah=\'blah\'
['test.py', "blah='blah'"]

该行为是否与操作系统无关? - Bleeding Fingers
非常正确。这取决于shell的实现。在Windows上,cmd控制台引用使用不同于bash shell的规则。我对tshzsh的经验很少,但它们可能会再次使用不同的规则。 - Martijn Pieters

1

或许

python test.py blah="'blah'"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接