Notice
Recent Posts
Recent Comments
Link
SeouliteLab
[Python/파이썬] Shell 명령어 실행 및 리턴 값 받기 본문
Python에서는 subprocess
모듈을 사용하여 쉘 명령어를 실행하고 그 결과를 가져올 수 있습니다. 이 모듈은 쉘 환경에서 외부 프로세스를 실행하고 통제하는 데 사용됩니다.
1. 단일 명령어 실행
하나의 명령어를 실행하고 결과를 가져오는 예제입니다. subprocess.run()
함수를 사용하여 쉘 명령어를 실행하고 표준 출력을 반환합니다.
import subprocess
result = subprocess.run(['ls', '-l'], capture_output=True, text=True)
print(result.stdout)
2. 여러 명령어 실행
여러 명령어를 연결하여 실행하고 결과를 가져오는 예제입니다. 파이프 라인을 사용하여 명령어를 연결하고, subprocess.Popen()
을 사용하여 실행합니다.
import subprocess
commands = [
'echo "Hello, World!"',
'grep World',
]
p1 = subprocess.Popen(commands[0], stdout=subprocess.PIPE, shell=True)
p2 = subprocess.Popen(commands[1], stdin=p1.stdout, stdout=subprocess.PIPE, shell=True)
p1.stdout.close() # p1의 출력을 닫아줍니다.
output = p2.communicate()[0]
print(output.decode())
3. Shell 변수 사용
쉘 변수를 사용하여 명령어를 실행하는 예제입니다. subprocess.run()
함수에 shell=True
옵션을 사용하여 쉘 변수를 확장할 수 있습니다.
import subprocess
result = subprocess.run('echo $HOME', capture_output=True, text=True, shell=True)
print(result.stdout)
'프로그래밍' 카테고리의 다른 글
[Python/파이썬] Stack trace 출력하는 방법 (traceback) (0) | 2024.03.05 |
---|---|
[Python/파이썬] 숫자 3자리마다 콤마(,) 넣는 방법 (0) | 2024.03.05 |
[Python/파이썬] 데이터 Type 확인 - type(), isinstance() (0) | 2024.03.05 |
[Python/파이썬] 두 변수 값 바꾸기(Swap) (0) | 2024.03.05 |
[Python/파이썬] 제곱근 계산 방법 (0) | 2024.03.05 |