Timeout on subprocess readline in Python

后端 未结 6 2109
既然无缘
既然无缘 2020-12-12 22:18

I have a small issue that I\'m not quite sure how to solve. Here is a minimal example:

What I have

scan_process = subprocess.Popen(command, stdout=su         


        
6条回答
  •  鱼传尺愫
    2020-12-12 23:00

    While Tom's solution works, using select() in the C idiom is more compact, this is the equivalent of your answer:

    from select import select
    scan_process = subprocess.Popen(command,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT,
                                    bufsize=1)  # Line buffered
    while some_criterium and not time_limit:
        poll_result = select([scan_process.stdout], [], [], time_limit)[0]
    

    The rest is the same.

    See pydoc select.select.

    [Note: this is Unix-specific, as are some of the other answers.]

    [Note 2: edited to add line buffering as per OP request]

    [Note 3: the line buffering may not be reliable in all circumstances, leading to readline() blocking]

提交回复
热议问题