代码之家  ›  专栏  ›  技术社区  ›  NutCracker

如何从其中读取python脚本的标准输出?

  •  1
  • NutCracker  · 技术社区  · 7 年前

    这是我的问题。我有一个应用程序,它使用 logging 模块。现在,我希望能够同时读取这些跟踪,以便等待我需要的特定跟踪。

    这是为了测试的目的。例如,如果想要的跟踪在大约2秒钟内没有发生,那么测试将失败。

    我知道我可以通过这样的方式读取其他脚本的输出:

    import subprocess
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while True:
        line = p.stdout.readline()
        print line
        if line == '' and p.poll() != None:
            break
    

    但是,我怎么能从脚本本身做类似的事情呢? 提前谢谢。

    编辑

    因此,由于我的问题是希望在python应用程序运行时出现某些跟踪,并且由于我无法从应用程序本身找到简单的方法来执行此操作,所以我决定从另一个脚本启动应用程序(如注释中所建议的)。

    我发现这个模块非常有用,而且比 subprocess 模块,IS pexpect 模块。

    3 回复  |  直到 7 年前
        1
  •  2
  •   vladmihaisima    7 年前

    如果要对记录器消息进行一些预处理,可以执行以下操作:

    #!/usr/bin/python
    
    import sys
    import logging
    import time
    import types
    
    def debug_wrapper(self,msg):
      if( hasattr(self,'last_time_seen') and 'message' in msg):
        print("INFO: seconds past since last time seen "+str(time.time()-self.last_time_seen))
      self.last_time_seen = time.time()
      self.debug_original(msg)
    
    logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
    logger = logging.getLogger("test")
    
    logger.debug_original = logger.debug
    logger.debug = types.MethodType(debug_wrapper, logger)
    
    while True:
      logger.debug("INFO: some message.")
      time.sleep(1)
    

    这可以通过将logger对象的原始调试函数替换为自定义调试包装函数来工作,在该函数中,您可以执行任何所需的处理,例如,存储上次看到消息的时间。

        2
  •  0
  •   rocksportrocker    7 年前

    如果要在其他python代码中记录print语句的输出,可以重定向 sys.stdout 要按如下方式字符串化文件对象:

    import io
    import sys
    
    def foo():
        print("hello world, what else ?")
    
    stream = io.StringIO()
    sys.stdout = stream
    try:
        foo()
    finally:
        sys.stdout = sys.__stdout__
    
    print(stream.getvalue())
    
        3
  •  0
  •   Prashant Gupta    7 年前

    您可以将脚本输出实时存储到文件中,然后实时读取脚本中的内容(因为输出文件中的内容正在动态更新)。

    要将脚本输出实时存储到文件中,可以使用expect包附带的unbuffer。

    sudo apt-get install expect
    

    然后,在运行脚本时使用:

    unbuffer python script.py > output.txt
    

    您只需在脚本中打印输出,脚本将动态更新为输出文件。因此,每次都要读那个文件。

    此外,还可以使用>覆盖旧文件或创建新文件,>>附加先前创建的output.txt文件中的内容。