【问题标题】:How to get what was printed inside an eval in python?如何获取在 python 中的 eval 中打印的内容?
【发布时间】:2019-11-24 15:27:45
【问题描述】:

我正在制作一个 Discord Bot,并且想知道是否有可能获得 eval 打印的内容

我知道您可以在 eval 开始时开始记录打印,并在 eval 完成时停止,这样您就可以得到在 eval 期间打印的内容,但是程序使用异步,如果我这样做,恐怕我也可以在 eval 之外打印一些东西。

有没有什么方法可以获取在一次评估期间打印的内容?

谢谢!

我知道使用 eval 不好,但我不是在问 eval 是好是坏。

【问题讨论】:

    标签: python python-3.x printing console eval


    【解决方案1】:

    我不敢相信我以前没有想到这一点。

    将 print 设置为您的函数,该函数既记录内容,然后将其传递给正常的 print 函数并让 eval 使用它,如下所示:

    try: #Imagine this was in a try
        printlog = []
        print = yourfunction #yourfunction appends to printlog prints that
                             #go through it and then prints them normally
        eval(stuff)
        #printlog now has what was printed
    

    这样,您将获得仅在该 eval 中打印的内容,无论其他任何内容同时运行。

    【讨论】:

      猜你喜欢
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多