Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何解析正在运行的命令的JSON输出?_Python_Json_Python 3.x_Parsing_Stream - Fatal编程技术网

Python 如何解析正在运行的命令的JSON输出?

Python 如何解析正在运行的命令的JSON输出?,python,json,python-3.x,parsing,stream,Python,Json,Python 3.x,Parsing,Stream,Summary:我想在输出时解析tshark的JSON输出 到现在为止,我正在逐行解析正常的输出,每一行都有完整的信息。因此,这是一个问题 p = subprocess.Popen("/usr/bin/tshark", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) for line in p.stdout: event = decode_even

Summary:我想在输出时解析
tshark
的JSON输出

到现在为止,我正在逐行解析正常的输出,每一行都有完整的信息。因此,这是一个问题

p = subprocess.Popen("/usr/bin/tshark", stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
     for line in p.stdout:
         event = decode_event(line)
tshark
还可以通过
-T JSON
开关输出打印精美的JSON(我只给出第一个数据包,输出是一个列表):

引发了一个例外

Traceback (most recent call last):
  File "/root/dev/readtshark.py", line 12, in <module>
    for message in messages:
  File "/usr/local/lib/python3.5/dist-packages/naya/json.py", line 544, in stream_array
    token_type, token = next(token_stream)
ValueError: too many values to unpack (expected 2)
回溯(最近一次呼叫最后一次):
文件“/root/dev/readtshark.py”,第12行,在
对于消息中的消息:
文件“/usr/local/lib/python3.5/dist-packages/naya/json.py”,第544行,在stream_数组中
令牌类型,令牌=下一个(令牌流)
ValueError:要解压缩的值太多(应为2个)
实际工作版本

#!/usr/bin/python3
# tshark.py
import json, sys, time

output = sys.stdin
acc = '{'

def skip(output):
    while True:
        l = output.readline()
        if l.strip() != '{':
            continue
        else:
            break


skip(output)
print("starting")
while True:
    l = output.readline()
    if l.strip() != '':
        acc += l.strip()
    try:
        o = json.loads(acc)
        print(o)
        skip(output)
        acc = '{'
    except:
        pass

用sudo tshark-i wlp3s0-T json |/tshark.py启动@omu_negrou的回答给了我一个想法,我最终使用了下面的解决方案

这基本上是一个对JSON进行解码的连续尝试,一旦它被解码,它就是我进一步处理的事件(这里,仅打印)


您真的不想将它连接到stdout吗?使用
jq
比Python快得多,只需将其输出导入that@omu_negru:当然可以,更正了。谢谢。在这种情况下,stdout是一个类似文件的对象,您应该能够将其传递给api…@eagle:解码后的数据包会发生很多事情,这只是一个开始,所以它需要一个Python脚本谢谢-您的回答启发了我另一个解决方案(也作为答案发布)
Traceback (most recent call last):
  File "/root/dev/readtshark.py", line 12, in <module>
    for message in messages:
  File "/usr/local/lib/python3.5/dist-packages/naya/json.py", line 544, in stream_array
    token_type, token = next(token_stream)
ValueError: too many values to unpack (expected 2)
#!/usr/bin/python3
# tshark.py
import json, sys, time

output = sys.stdin
acc = '{'

def skip(output):
    while True:
        l = output.readline()
        if l.strip() != '{':
            continue
        else:
            break


skip(output)
print("starting")
while True:
    l = output.readline()
    if l.strip() != '':
        acc += l.strip()
    try:
        o = json.loads(acc)
        print(o)
        skip(output)
        acc = '{'
    except:
        pass
import subprocess
import json


def handle_message(event):
    print(event)

cmd = "/usr/bin/tshark -n -T json not broadcast and not multicast"
proc = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
# skip first lines, until the [ which starts JSON
for line in proc.stdout:
    if line.decode().startswith('['):
        break
    else:
        continue

buffer = ""
for line in proc.stdout:
    # remove empty and "connection" lines (a comma)
    if not line.decode().strip(', \n'):
        continue
    buffer += line.decode('utf-8')
    try:
        event = json.loads(buffer)
    except json.decoder.JSONDecodeError:
        pass
    else:
        print(event)
        buffer = ""