处理键盘中断和文件写入

洛兰·萨特

我有一个应用程序,它几乎每秒都会监视来自 Web 的一些数据并写入文件。此应用程序 24/7 全天候运行,但有时我必须将其关闭。我在需要时使用键盘中断异常来停止应用程序,但有时应用程序没有完成文件写入并且我的文件已损坏。是什么让我修复文件以便在我再次打开它时让应用程序正常工作。

这是一段代码:

while True:
    try:
        conns = [http.client.HTTPSConnection(C.REQUEST_HOST) for k in range(C.num_coins)]

        for k in range(C.num_coins):
            conns[k].request("GET", C.REQUEST_PATH_TICKER.format(C.coin_types[k]))

        responses = [conns[k].getresponse().read() for k in range(C.num_coins)]
        responses_json_new = [
            json.loads(responses[k].decode(), object_pairs_hook=OrderedDict)
            for k in range(C.num_coins)
        ]
        responses_json_new = [responses_json_new[k]["ticker"] for k in range(C.num_coins)]

        for k in range(C.num_coins):
            if responses_json_new[k]["last"] != responses_json_old[k]["last"]:

                date_ticker = datetime.datetime.fromtimestamp(
                    int(responses_json_new[k]["date"])
                ).strftime("%Y-%m-%d")

            with open(files_path[k] + date_ticker + ".json", "a") as f:
                json.dump(responses_json_new[k], f)
                f.write("\n")

            responses_json_old[k] = responses_json_new[k]
            print(
                out.format(
                    C.coin_types[k],
                    float(responses_json_new[k]["vol"]),
                    float(responses_json_new[k]["last"]),
                    datetime.datetime.fromtimestamp(
                        responses_json_new[k]["date"]
                    ).strftime("%Y-%m-%d %H:%M:%S"),
                )
            )

        currentDate, files_path = updateFilePath(currentDate, files_path)
        time.sleep(1)

    except KeyboardInterrupt:
        print("\nInterrupted!\n")
        for k in range(C.num_coins):
            if conns[k]:
                conns[k].close()
        sys.exit()
    except Exception as e:
        print("\nERROR:", sys.exc_info()[0])
        ut.exception_log(e, traceback.format_exc())
        ut.close_waiting(conns, wait=30)
        continue

    finally:
        for k in range(C.num_coins):
            if conns[k]:
                conns[k].close()

我需要一些关于如何处理这个问题的建议。

谢谢大家!

AKX

.dump() 如果输出足够大,可以(显然)将输出分成几个块。

您需要.dumps()先编码为 JSON 字符串,然后再编码为.write()文件。

为了证明输出可以写成多个块,让我们strace在 Docker 容器中启动,看看什么得到write()d。

(host) $ docker run -it ubuntu:18.04 bash
# apt install strace python3
# cat > ex1.py

import json, sys
payload = [[x] * x for x in range(5, 10)] * 250
json.dump(payload, sys.stdout)

# strace python3 ex1.py >/dev/null

(uninteresting lines redacted)
write(1, "[[5, 5, 5, 5, 5], [6, 6, 6, 6, 6"..., 8194) = 8194
write(1, ", 6, 6], [7, 7, 7, 7, 7, 7, 7], "..., 8194) = 8194
write(1, "], [8, 8, 8, 8, 8, 8, 8, 8], [9,"..., 8194) = 8194
write(1, "[9, 9, 9, 9, 9, 9, 9, 9, 9], [5,"..., 4168) = 4168

# cat > ex2.py

import json, sys
payload = [[x] * x for x in range(5, 10)] * 250
pl2 = json.dumps(payload)
sys.stdout.write(pl2)

# strace python3 ex2.py 

(uninteresting lines redacted)
write(1, "[[5, 5, 5, 5, 5], [6, 6, 6, 6, 6"..., 28750) = 28750

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Perl处理键盘中断

来自分类Dev

键盘中断与python的多处理

来自分类Dev

键盘中断与python的多处理

来自分类Dev

自己内核的键盘中断处理程序(C)

来自分类Dev

在异步ZMQ中处理键盘中断

来自分类Dev

文件写入异常处理

来自分类Dev

熊猫groupby和文件写入问题

来自分类Dev

在python上并行执行和文件写入

来自分类Dev

python解码和文件写入问题

来自分类Dev

Debian:允许写入目录和文件

来自分类Dev

传输远程GUI和文件处理(transgui)

来自分类Dev

Python多处理和文件查找

来自分类Dev

python 处理 xlsx 工作表和文件?

来自分类Dev

处理文件的并发读取/写入

来自分类Dev

C#文本文件浏览和文件写入

来自分类Dev

文件写入器和文件读取器错误

来自分类Dev

如何将文件和文件路径写入表

来自分类Dev

php中的文件创建和文件写入

来自分类Dev

Python-多重处理和文本文件处理

来自分类Dev

使用 dictConfig 记录并写入控制台和文件

来自分类Dev

文件之间的中断批处理作业

来自分类Dev

用键盘中断rm命令会删除任何文件吗?

来自分类Dev

如何写入文件,以批处理方式写入文件

来自分类Dev

清空文件而不中断管道对其的写入

来自分类Dev

将ping写入文件批处理

来自分类Dev

python多处理写入共享文件

来自分类Dev

写入文件并处理重复条目

来自分类Dev

处理以块方式写入C中的文件

来自分类Dev

批处理文件写入txt