python - 如何使用 Python shlex 解析 bash 数组?

标签 python arrays bash lexical-analysis shlex

输入:

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/

相关文章:

bash - 从 Bash 中的目录读取文件名

linux - 如何将 shell 脚本部署到私有(private) Linux 虚拟机

python - 基于另外两个列表在 Python 中创建列表?

python - 在__init__中设置self.var时发生Python错误

javascript - 将新属性添加到另一个具有不同长度的数组的对象数组中,因此一旦数组完成迭代,它将再次从第一个开始

arrays - 如何在 Google Sheet 的 App Script 中创建数组的真正新副本?

python - python应用程序中脚本目录的成语?

python - 为 pandas DataFrame 中的每一行选择非空列

arrays - JSON 数组不会快速显示在 UITable 中

android - protobyname 错误的任何解决方法?