简体   繁体   English

如何实时解析预期?

[英]How can I parse pexpect in real time?

I'm considering pexpect (totally open to alternatives, if there are better ones I'm not aware of) in one of our deploy script wrappers -- but I need a way to read the output in real-time, not only once we've hit the EOF . 我正在考虑在我们的一个部署脚本包装器中使用pexpect (如果没有其他更好的选择,则完全开放给其他选择),但我需要一种实时读取输出的方法,不仅是一次已经击中了EOF Since this is a deployment package, used for all environments, we need to catch issues as soon as they happen (and potentially hit the emergency exit if it's really bad). 由于这是一个部署包,适用于所有环境,因此我们需要尽快发现问题(如果情况真的很糟,有可能击中紧急出口)。

Is there such a thing I can use? 我可以使用这种东西吗? Ideally, I'd like to make use of our already existing logger.. 理想情况下,我想利用我们现有的记录器。

def SetupLogging():
    # the logger
    # set to DEBUG since the reports should already give
    # any information we're looking for at a glance
    global log 
    log = logging.getLogger('ansiwrap')
    log.setLevel(logging.DEBUG)

    # create file handler which logs everything
    fh = logging.FileHandler('ansiwrap.debug', mode='w')
    fh.setLevel(logging.DEBUG)

    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)

    # create formatter and add it to the handlers
    formatter = logging.Formatter('[%(asctime)s] | %(name)s - %(levelname)s - %(message)s')
    ch.setFormatter(formatter)  
    fh.setFormatter(formatter)

    # add the handlers to logger
    log.addHandler(ch)
    log.addHandler(fh)

For completeness, here is an example implementation, but it seems clunky to me: 为了完整起见,这是一个示例实现,但是对我来说似乎很笨拙:

child = pexpect.spawn(cmd)
while True:
    try:
        child.expect('\n')
        print(child.before)
    except pexpect.EOF:
        break 

EOF is hit when the child process terminates. 子进程终止时,将命中EOF To get real time output of the commands being sent and replies received, you can log the output to stdout or a file. 要获得正在发送的命令和收到的答复的实时输出,可以将输出记录到stdout或文件中。

Spawn class of Pexpect has a logfile_read attribute which writes the output of child process to the file specified. Pexpect的Spawn类具有logfile_read属性,该属性将子进程的输出写入指定的文件。 Modifying the code as shown below will do the job. 如下所示修改代码即可完成这项工作。 I am using sys.stdout which will print everything to the console. 我正在使用sys.stdout它将所有内容打印到控制台。 You can open a file and use that as well 您可以打开一个文件并使用它

child = pexpect.spawn(cmd)
child.logfile_read = sys.stdout
while True:
    try:
        child.expect('\n')
        print(child.after)
    except pexpect.EOF:
        break 

The reason the while block is still needed is because as per documentation logfile is flushed after every write. 仍然需要while块的原因是因为每次写入后都会刷新文档日志文件。 Since writes are not there, a call to expect will cause the flushing to the file. 由于不存在写操作,因此期望调用将导致刷新文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM