Python sys.argv保留“”或“”


问题内容

终奌站:

python test.py blah='blah'

在test.py中

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

等等arg如何保留其’‘或
是否有办法知道arg是用“”还是”包装?


问题答案:

您的 外壳 在调用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'"]