본문 바로가기

파이선에서 서브프로세스를 실행시키고 출력되는 결과를 가져오는 방법입니다.


예제는 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


건투를 빕니다!







번호 제목 날짜 조회 수
HOT [TIP] PYTHON 에서 "UnicodeDecodeError: 'cp949' codec can't decode byte 0xe2 in position 6987: illegal multibyte sequence" 오류 날때... [52] 2016.02.20 266423
HOT [펌] ARM GCC Inline Assembler Cookbook 2006.08.18 57948
HOT [TIP] R에서 페이스북 페이지 정보 크롤링 하기 [6] 2017.02.11 39875
150 [TIP] 파이선에서 AWS Lambda로 만든 Restful API 호출하기 (How to call AWS Lambda Restful API from Python) 2018.01.23 2830
» [TIP] 파이선에서 서브프로세스를 실행시키고 출력되는 내용을 얻어오기 2018.01.22 12724
148 [TIP] 아두이노에서 AWS Lambda로 제작한 Restful API 호출하기 (The way how to call AWS Lambda Restful API from Arduino) 2018.01.18 2519
147 [TIP] 파이선에서 Redis 이벤트 받기 2017.10.12 2016
146 [TIP] 파이선에서 SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position ... 오류 해결 방법 2017.09.29 3434
145 [TIP] The function size must be used with a prefix when a default namespace is not specified 오류 해결하기 2017.08.02 4372
144 [TIP] 페이스북 개인 담벼락의 좋아요수 크롤링하기 2017.07.15 2551
143 [TIP] 자바스크립트와 PHP코드간에 암호화 통신하기 (Encrypt with Javascript, Decrypt with PHP) [2] 2017.03.16 6160
142 [TIP] GUNMAN의 영화 점수 테이블을 이용한 딥러닝 예제 2017.02.15 3215
141 [TIP] R에서 페이스북 페이지 정보 크롤링 하기 [6] 2017.02.11 39875
140 [TIP] 네이버 영화 정보와 전문가 평점 얻어오기 2017.02.10 8740
139 [TIP] 네이버 오픈 API를 로컬 PC에서 호출하기 2017.02.01 4448
138 [TIP] php로 기상청에서 제공하는 기상정보 API 호출하기 2017.01.17 10710
137 [TIP] node 에서 Basic authentication 인증과 함께 http, https 요청하기 2016.09.01 2722
136 [TIP] node의 lambda-local 테스트 팁 2016.08.19 1941
135 [TIP] 데이터를 Node에서 암호화하고 PHP에서 복호화 하기 2016.08.19 2122
134 [TIP] Docker상의 Syntaxnet 결과 포맷을 수정하기 2016.08.07 3172
133 [TIP] SyntaxNet을 Windows에서 실행하기 [1] 2016.05.25 2104
132 [TIP] TensorFlow를 윈도우에서 사용하기 (A way to use TensorFlow on Windows) [3] 2016.04.16 23513
131 [TIP] 파이선으로 TED에서 가장많이 사용된 단어들 줄세우기 2016.04.03 2680