파이선에서 서브프로세스를 실행시키고 출력되는 결과를 가져오는 방법입니다.
예제는 wireshark 를 실행시켜 tcp 패킷을 캡쳐할때마다 그 출력을 파이선으로 가지고 오는 코드입니다.
#!/usr/bin/env python
import subprocess
from time import sleep
def run_command(command):
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)
# Read stdout from subprocess until the buffer is empty !
for line in iter(p.stdout.readline, b''):
if line: # Don't print blank lines
yield line
# This ensures the process has completed, AND sets the 'returncode' attr
while p.poll() is None:
sleep(.1) #Don't waste CPU-cycles
# Empty STDERR buffer
err = p.stderr.read()
if p.returncode != 0:
# The run_command() function is responsible for logging STDERR
print("Error: " + str(err))
for line in run_command('tshark -nni en0 -Y tcp'):
print(line)참고자료: https://stackoverflow.com/questions/4760215/running-shell-command-from-python-and-capturing-the-output/23187248
건투를 빕니다!