当args包含单引号和双引号时,如何将命令args传递给python脚本?

how to pass command args to python scripts when the args contains the Single quotes and Double quotation marks?

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)'s result, i use json.loads to load the '[" =21=]"]'.

但是我怎样才能传递我想要的字符串呢?

此问题与程序语言无关,例如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", line 7, 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 中不行。