问题描述
import sys
import json
if __name__ == '__main__':
print(sys.argv)
print(json.loads(sys.argv[1]))
结果:
(env) λ python main.py '["br_V1R22C00RR1_bugfix"]'
['main.py',"'[br_V1R22C00RR1_bugfix]'"]
Traceback (most recent call last):
File "C:\Users\x\PycharmProjects\GaussClientUpgrade\main.py",line 30,in <module>
print(json.loads(sys.argv[1]))
File "c:\users\x\appdata\local\programs\python\python39\lib\json\__init__.py",line 346,in loads
return _default_decoder.decode(s)
File "c:\users\x3\appdata\local\programs\python\python39\lib\json\decoder.py",line 337,in decode
obj,end = self.raw_decode(s,idx=_w(s,0).end())
File "c:\users\x\appdata\local\programs\python\python39\lib\json\decoder.py",line 355,in raw_decode
raise JSONDecodeError("Expecting value",s,err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
我想传递一个像 '["br_V1R22C00RR1_bugfix"]' 这样的字符串,不要消除 ' 和 ",这是一个 json.dumps(list) 的结果,我使用 json.loads 来加载 '["br_V1R22C00RR1_bugfix "]'。
但是我怎样才能传递我想要的字符串?
解决方法
这个问题与程序语言无关,例如也可以在 Java 中发生。
这是因为 bash 和 dos 之间的参数处理不同。
在Linux中:
[root@clarence lib]# python test.py \"['br']\"
"[br]"
[br]
[root@clarence lib]# python test.py '["br"]'
["br"]
['br']
[root@clarence lib]# python test.py [\"br\"]
["br"]
['br']
[root@clarence lib]# python test.py "[\"br\"]"
["br"]
['br']
[root@clarence lib]# python test.py "['br']"
['br']
Traceback (most recent call last):
File "test.py",line 7,in <module>
print(json.loads(sys.argv[1]))
File "/usr/lib64/python3.7/json/__init__.py",line 348,in loads
return _default_decoder.decode(s)
File "/usr/lib64/python3.7/json/decoder.py",line 337,in decode
obj,end = self.raw_decode(s,idx=_w(s,0).end())
File "/usr/lib64/python3.7/json/decoder.py",line 355,in raw_decode
raise JSONDecodeError("Expecting value",s,err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)
[root@clarence lib]# python test.py "[\"br\"trer't]"
["br"trer't]
Traceback (most recent call last):
在 windows dos 中:
(env) λ python test.py \"['br']\"
"['br']"
['br']
(env) λ python test.py '["br"]'
'[br]'
Traceback (most recent call last):
File "C:\Users\clarence\Desktop\test.py",in <module>
print(json.loads(sys.argv[1]))
(env) λ python test.py [\"br\"]
["br"]
['br']
(env) λ python test.py "[\"br\"]"
["br"]
['br']
(env) λ python test.py "['br']"
['br']
Traceback (most recent call last):
python test.py '["br"]' 在bash中可以成功运行,但在dos中不能。