输入:
declare -a ForwardPort=([0]="L *:9102:10.0.1.8:9100 # remote laptop" [1]="L *:9166:8.8.8.8:9100 # google")
期望的输出
我想得到这个输出:
{
'ForwardPort': [
'"L *:9102:10.0.1.8:9100 # remote laptop"',
'"L *:9166:8.8.8.8:9100 # google"'
]
}
尝试
我尝试玩一下shlex
,但是数组的解析很糟糕:
import shlex
line='ForwardPort=([0]="L *:9102:10.0.1.8:9100 # remote laptop" [1]="L *:9166:8.8.8.8:9100 # google")'
lex=shlex.shlex(line)
list(lex)
['ForwardPort', '=', '(', '[', '0', ']', '=', '"L *:9102:10.0.1.8:9100 # remote laptop"', '[', '1', ']', '=', '"L *:9166:8.8.8.8:9100 # google"', ')']
问题
有没有办法自动将ForwardPort
的值解析到列表中?
注意:不要在家里重现,这是一个糟糕的设计决策,导致了这个复杂的问题:S
最佳答案
你可以在 bash 中打印出来:
#!/bin/bash
declare -a ForwardPort=([0]="L *:9102:10.0.1.8:9100 # remote laptop" [1]="L *:9166:8.8.8.8:9100 # google")
res=$(python -c 'import json, sys; print(json.dumps({"ForwardPort": [v for v in sys.argv[1:]]}))' "${ForwardPort[@]}")
echo "$res"
给出:
{"ForwardPort": ["L *:9102:10.0.1.8:9100 # remote laptop", "L *:9166:8.8.8.8:9100 # google"]}
<小时/>
如果你在 python 中将 bash 数组定义为字符串,你可以尝试这个有点粗略的解析:
import re
line='ForwardPort=([0]="L *:9102:10.0.1.8:9100 # remote laptop" [1]="L *:9166:8.8.8.8:9100 # google")'
name, arr = line.split('=(')
arr = arr[:-1] # removing the trailing ')'
lst = [item for item in re.split('\[\d+\]=', arr) if item]
dct = {name: lst}
print(dct)
关于python - 如何使用 Python shlex 解析 bash 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52817560/