python打开功能使输出三合一功能

发布于 2025-02-12 12:48:08 字数 2358 浏览 0 评论 0原文

我对Python和编码非常陌生,因此,任何帮助或指向正确方向的任何帮助都将受到极大的赞赏。

我正在尝试使用Python的开放函数将输出打印到文件。当我将“ JSTAT_OUTPUT”变量打印到终端时,它看起来不错,但是当我尝试读取文本文件时,它已被截断。

代码:

with open(path_to_file, 'w', newline='') as o:
for item in jstat_output:
    o.write(f'{item}\n')

终端输出:

[Container(PayloadLength=81, Payload=u'  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT   '), Container(PayloadLength=81, Payload=u'  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT   ')]

记事本查看器:

容器: PAYLOADLENGTH = 81 有效载荷= u's0 s1 eom'...(截断,总计81) 容器: PAYLOADLENGTH = 81 有效载荷= U'S0 S1 EOM'...(截断,总计81)

如果有人知道为什么会发生这种情况,或者也许是写入文件的另一种方法,那将是巨大的帮助;谢谢。

    for pid in extracted_numbers:
        exec_resp = ecs.execute_command(
            cluster=f'{clusterArn[0]}',
            container=f'{containerNames[ttype]}',
            task=f'{tArns[tarn]}',
            command=f'jstat -gcutil {pid} 250',
            interactive=True
    )
    session = exec_resp['session']
    connection = websocket.create_connection(session['streamUrl'])
    try:
        init_payload = {
            "MessageSchemaVersion": "1.0",
            "RequestId": str(uuid.uuid4()),
            "TokenValue": session['tokenValue']
        }
        connection.send(json.dumps(init_payload))

        AgentMessageHeader = c.Struct(
            'HeaderLength' / c.Int32ub,
            'MessageType' / c.PaddedString(32, 'ascii'),
        )

        AgentMessagePayload = c.Struct(
            'PayloadLength' / c.Int32ub,
            'Payload' / c.PaddedString(c.this.PayloadLength, 'ascii')
        )

        while True:
            response = connection.recv()

            message = AgentMessageHeader.parse(response)

            if 'channel_closed' in message.MessageType:
                raise Exception('Channel closed before command output was received')

            if 'output_stream_data' in message.MessageType:
                break
    finally:
        connection.close()

    payload_message = AgentMessagePayload.parse(response[message.HeaderLength:])
    jstat_output.append(payload_message)

print(jstat_output)
with open(path_to_file, openvar, newline='') as o:
    print(f'{jstat_output}', file=o)

这是与问题相关的代码的一部分。

I am very new to python and coding in general, so any help or point in the right direction is greatly appreciated.

I am trying to print an output to a file using python's open function. when I print the 'jstat_output' variable to the terminal it appears fine, but when I try to read the textfile it has been truncated.

the code:

with open(path_to_file, 'w', newline='') as o:
for item in jstat_output:
    o.write(f'{item}\n')

terminal output:

[Container(PayloadLength=81, Payload=u'  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT   '), Container(PayloadLength=81, Payload=u'  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT   ')]

notepad viewer:

Container:
PayloadLength = 81
Payload = u' S0 S1 E O M '... (truncated, total 81)
Container:
PayloadLength = 81
Payload = u' S0 S1 E O M '... (truncated, total 81)

if anyone knows why this happens, or perhaps a different method to write to a file it would be a massive help; thanks.

    for pid in extracted_numbers:
        exec_resp = ecs.execute_command(
            cluster=f'{clusterArn[0]}',
            container=f'{containerNames[ttype]}',
            task=f'{tArns[tarn]}',
            command=f'jstat -gcutil {pid} 250',
            interactive=True
    )
    session = exec_resp['session']
    connection = websocket.create_connection(session['streamUrl'])
    try:
        init_payload = {
            "MessageSchemaVersion": "1.0",
            "RequestId": str(uuid.uuid4()),
            "TokenValue": session['tokenValue']
        }
        connection.send(json.dumps(init_payload))

        AgentMessageHeader = c.Struct(
            'HeaderLength' / c.Int32ub,
            'MessageType' / c.PaddedString(32, 'ascii'),
        )

        AgentMessagePayload = c.Struct(
            'PayloadLength' / c.Int32ub,
            'Payload' / c.PaddedString(c.this.PayloadLength, 'ascii')
        )

        while True:
            response = connection.recv()

            message = AgentMessageHeader.parse(response)

            if 'channel_closed' in message.MessageType:
                raise Exception('Channel closed before command output was received')

            if 'output_stream_data' in message.MessageType:
                break
    finally:
        connection.close()

    payload_message = AgentMessagePayload.parse(response[message.HeaderLength:])
    jstat_output.append(payload_message)

print(jstat_output)
with open(path_to_file, openvar, newline='') as o:
    print(f'{jstat_output}', file=o)

this is the portion of the code that is related to the problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风柔一江水 2025-02-19 12:48:08

您的print()打印非截断版本的原因是,它正在打印每个项目的repr()而不是str()它。

我相信这将做您想要的事情:

with open(path_to_file, 'w') as o:
    for item in jstat_output:
        o.write(repr(item) + "\n")

线索是JSTAT_OUTPUT是列表,当您打印它时:

print(jstat_output)

您获得了所需的输出。

当将列表渲染为字符串时,它将呈现其每个单个项目的repr()。如果项目是单独格式的(例如,通过执行f“ {item}”print(item)),而是获得他们的str()str()< /代码>表示。在这种情况下,当项目较大时,str()表示表示,而repr()包括整个内容。因此,明确调用repr(item)而不是使用F-string,因此应该为您提供所需的输出。只要将repr()放入{},即n“

一个更好的解决方案可能是编写自己的功能,以所需格式输出容器,而不是依靠其__ epr __实现,但这需要能够看到定义容器

The reason that your print() prints the non-truncated version is that it's printing the repr() of each item instead of the str() of it.

I believe this will do what you want:

with open(path_to_file, 'w') as o:
    for item in jstat_output:
        o.write(repr(item) + "\n")

The clue is that jstat_output is a list and when you printed it with:

print(jstat_output)

you got the desired output.

When a list is rendered as a string, it renders the repr() of each of its individual items. If the items are formatted individually (e.g. by doing f"{item}" or print(item)), you're instead getting their str() representation. In this case, the str() representation is truncated when the item is large, whereas repr() includes the whole thing. Explicitly calling repr(item) instead of using an f-string should therefore get you the output you're looking for. You could also still use an f-string as long as you put the repr() inside the {}, i.e. f"{repr(item)}\n".

A better solution might be to write your own function to output a Container in the desired format rather than relying on its __repr__ implementation, but that would require being able to see the definition of the Container class.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文