Skip to content

Python:subprocess

Use the os.system

이 방법은 반환값으로 프로그램 실행 결과코드1가 반환된다.

import os
print os.system('example.exe')

Use the os.popen

os.popen 시리즈는 python 2.0에 생겨서 2.6이 되면서 subprocess의 popen으로 바꿔 쓰기를 권장한다. subprocess는 2.4 버전에 생겼다.

import os

def execute(cmd):
    std_in, std_out, std_err = os.popen3(cmd)
    return std_out, std_err

cmd = "ls -l"

std_out, std_err = execute(cmd)
for line in std_out.readlines():
    print line

Use the subprocess

import subprocess

def execute(cmd) :
    fd = subprocess.Popen(cmd, shell=True,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE)
    return fd.stdout, fd.stderr

cmd = "ls -l"

std_out, std_err = execute(cmd)
for line in std_out.readlines():
    print line

See also

Favorite site

References


  1. Bash의 $?값.