찾다
백엔드 개발파이썬 튜토리얼Python에서 프로세스 출력을 중지할 때 Readline 중단을 방지하는 방법은 무엇입니까?

How to Avoid Readline Hangs When Stopping Process Output in Python?

Python에서 프로세스 출력을 중지할 때 Readline 중단 방지

문제 설명:

os.popen을 사용하는 Python 프로그램에서 () 또는 subprocess.Popen()을 사용하여 지속적으로 업데이트되는 프로세스(예: top)의 출력을 읽으려는 경우, readlines()를 사용하여 모든 줄을 읽으려고 하면 프로그램이 중단될 수 있습니다.

해결책:

임시 파일 및 하위 프로세스 사용:

<code class="python">import subprocess
import tempfile
import time

def main():
    # Open a temporary file for process output
    with tempfile.TemporaryFile() as f:
        # Start the process and redirect its stdout to the file
        process = subprocess.Popen(["top"], stdout=f)

        # Wait for a specified amount of time
        time.sleep(2)

        # Kill the process
        process.terminate()
        process.wait()  # Wait for the process to terminate to ensure complete output

        # Seek to the beginning of the file and print its contents
        f.seek(0)
        print(f.read())

if __name__ == "__main__":
    main()</code>

이 접근 방식은 임시 파일을 사용하여 프로세스 출력을 저장하므로 프로그램이 readlines()에서 차단되는 것을 방지할 수 있습니다.

대체 솔루션:

다른 스레드와 함께 대기열 사용:

<code class="python">import collections
import subprocess
import threading

def main():
    # Create a queue to store process output
    q = collections.deque()

    # Start the process and redirect its stdout to a thread
    process = subprocess.Popen(["top"], stdout=subprocess.PIPE)
    t = threading.Thread(target=process.stdout.readline, args=(q.append,))
    t.daemon = True
    t.start()

    # Wait for a specified amount of time
    time.sleep(2)

    # Terminate the process
    process.terminate()
    t.join()  # Wait for the thread to finish

    # Print the stored output
    print(''.join(q))

if __name__ == "__main__":
    main()</code>

signal.alarm() 사용:

<code class="python">import collections
import signal
import subprocess

class Alarm(Exception):
    pass

def alarm_handler(signum, frame):
    raise Alarm

def main():
    # Create a queue to store process output
    q = collections.deque()

    # Register a signal handler to handle alarm
    signal.signal(signal.SIGALRM, alarm_handler)

    # Start the process and redirect its stdout
    process = subprocess.Popen(["top"], stdout=subprocess.PIPE)

    # Set an alarm to terminate the process after a specified amount of time
    signal.alarm(2)

    # Read lines until the alarm is raised or the process terminates
    try:
        while True:
            line = process.stdout.readline()
            if not line:
                break
            q.append(line)
    except Alarm:
        process.terminate()

    # Cancel the alarm if it hasn't already fired
    signal.alarm(0)

    # Wait for the process to finish
    process.wait()

    # Print the stored output
    print(''.join(q))

if __name__ == "__main__":
    main()</code>

이러한 대안을 사용하면 프로세스 출력을 저장하는 동안 프로그램이 계속 실행될 수 있습니다. 프로세스 출력을 지속적으로 모니터링해야 하는 경우에 더 적합할 수 있습니다.

위 내용은 Python에서 프로세스 출력을 중지할 때 Readline 중단을 방지하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Numpy 배열은 배열 모듈을 사용하여 생성 된 배열과 어떻게 다릅니 까?Apr 24, 2025 pm 03:53 PM

numpyarraysarebetterfornumericaloperations 및 multi-dimensionaldata, mumemer-efficientArrays

Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Numpy Array의 사용은 Python에서 어레이 모듈 어레이를 사용하는 것과 어떻게 비교됩니까?Apr 24, 2025 pm 03:49 PM

numpyarraysarebetterforheavynumericalcomputing, whilearraymoduleisiMoresuily-sportainedprojectswithsimpledatatypes.1) numpyarraysofferversatively 및 formanceforgedatasets 및 complexoperations.2) Thearraymoduleisweighit 및 ep

CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?CTYPES 모듈은 파이썬의 어레이와 어떤 관련이 있습니까?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingandmanipulatingC-stylearraysinPython.1)UsectypestointerfacewithClibrariesforperformance.2)CreateC-stylearraysfornumericalcomputations.3)PassarraystoCfunctionsforefficientoperations.However,becautiousofmemorymanagement,performanceo

파이썬의 맥락에서 '배열'및 '목록'을 정의하십시오.파이썬의 맥락에서 '배열'및 '목록'을 정의하십시오.Apr 24, 2025 pm 03:41 PM

Inpython, "목록", isaversatile, mutablesequencetatcanholdmixeddatattypes, whilean "array"isamorememory-efficed, homogeneouseceenceRequiringElements ofthesAmeType.1) ListSareIdeAldiversEdatastorageandmanipulationDuetoIrflexibrieth

파이썬 목록은 변이 가능합니까? 파이썬 어레이는 어떻습니까?파이썬 목록은 변이 가능합니까? 파이썬 어레이는 어떻습니까?Apr 24, 2025 pm 03:37 PM

PythonlistsAndarraysareBotheBotheBothebothable.1) ListSareflexibleandsupporterogenousDatabutarabestemory-efficient.2) Arraysaremorememory-efforhomogeneousdatabutlessverstile, CorrectTypecodeusagetoavoidercer가 필요합니다.

Python vs. C : 주요 차이점 이해Python vs. C : 주요 차이점 이해Apr 21, 2025 am 12:18 AM

Python과 C는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구 사항을 기반으로해야합니다. 1) Python은 간결한 구문 및 동적 타이핑으로 인해 빠른 개발 및 데이터 처리에 적합합니다. 2) C는 정적 타이핑 및 수동 메모리 관리로 인해 고성능 및 시스템 프로그래밍에 적합합니다.

Python vs. C : 프로젝트를 위해 어떤 언어를 선택해야합니까?Python vs. C : 프로젝트를 위해 어떤 언어를 선택해야합니까?Apr 21, 2025 am 12:17 AM

Python 또는 C를 선택하는 것은 프로젝트 요구 사항에 따라 다릅니다. 1) 빠른 개발, 데이터 처리 및 프로토 타입 설계가 필요한 경우 Python을 선택하십시오. 2) 고성능, 낮은 대기 시간 및 근접 하드웨어 제어가 필요한 경우 C를 선택하십시오.

파이썬 목표에 도달 : 매일 2 시간의 힘파이썬 목표에 도달 : 매일 2 시간의 힘Apr 20, 2025 am 12:21 AM

매일 2 시간의 파이썬 학습을 투자하면 프로그래밍 기술을 효과적으로 향상시킬 수 있습니다. 1. 새로운 지식 배우기 : 문서를 읽거나 자습서를 시청하십시오. 2. 연습 : 코드를 작성하고 완전한 연습을합니다. 3. 검토 : 배운 내용을 통합하십시오. 4. 프로젝트 실무 : 실제 프로젝트에서 배운 것을 적용하십시오. 이러한 구조화 된 학습 계획은 파이썬을 체계적으로 마스터하고 경력 목표를 달성하는 데 도움이 될 수 있습니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구