programing

subprocess.run()의 출력을 억제하거나 캡처하는 방법은 무엇입니까?

instargram 2023. 5. 2. 22:17
반응형

subprocess.run()의 출력을 억제하거나 캡처하는 방법은 무엇입니까?

의 문서에 있는 예제를 보면 에서 출력이 없어야 할 것 같습니다.

subprocess.run(["ls", "-l"])  # doesn't capture output

하지만 파이썬 쉘에서 시도해보면 리스트가 출력됩니다.이것이 기본 동작인지 그리고 출력을 억제하는 방법이 궁금합니다.run().

다음은 청정도를 낮추기 위해 출력을 억제하는 방법입니다.그들은 당신이 파이썬 3에 있다고 가정합니다.

  1. 특수로 리디렉션할 수 있습니다.subprocess.DEVNULL표적이 되는
import subprocess

# To redirect stdout (only):
subprocess.run(['ls', '-l'], stdout=subprocess.DEVNULL)

# to redirect stderr to /dev/null as well:
subprocess.run(['ls', '-l'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

# Alternatively, you can merge stderr and stdout streams and redirect
# the one stream to /dev/null
subprocess.run(['ls', '-l'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
  1. 전체 수동 방법을 원하는 경우 다음으로 리디렉션할 수 있습니다./dev/null파일 핸들을 직접 열어 봅니다.다른 모든 것은 방법 #1과 동일합니다.
import os
import subprocess

with open(os.devnull, 'w') as devnull:
    subprocess.run(['ls', '-l'], stdout=devnull)

다음은 청정도를 줄이기 위해 출력을 캡처하는 방법(나중에 사용하거나 구문 분석)입니다.그들은 당신이 파이썬 3에 있다고 가정합니다.

참고: 아래의 예는 다음을 사용합니다.text=True.

  • 이로 인해 STDOUT 및 STDERR이 다음과 같이 캡처됩니다.str대신에bytes.
    • 생략text=True갖기 위해bytes데이터.
  • text=TruePython >= 3.7만 해당, 사용universal_newlines=TruePython <= 3.6에서
    • universal_newlines=True와 동일합니다.text=True그러나 입력하기에는 더 상세하지만 모든 파이썬 버전에 존재해야 합니다.
  1. 단순히 STDOUT와 STDERR을 모두 독립적으로 캡처하고 Python >= 3.7에 있는 경우,capture_output=True.
import subprocess

result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
print(result.stderr)
  1. 사용할 수 있습니다.subprocess.PIPESTDOUT 및 STDERR을 독립적으로 캡처합니다.이 기능은 다음을 지원하는 모든 버전의 Python에서 작동합니다.subprocess.run.
import subprocess

result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, text=True)
print(result.stdout)

# To also capture stderr...
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
print(result.stdout)
print(result.stderr)

# To mix stdout and stderr into a single string
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
print(result.stdout)

ex: 의 출력을 캡처합니다.ls -a

import subprocess
ls = subprocess.run(['ls', '-a'], capture_output=True, text=True).stdout.strip("\n")
print(ls)

언급URL : https://stackoverflow.com/questions/41171791/how-to-suppress-or-capture-the-output-of-subprocess-run

반응형