サンプルコード
私自身の勉強用です。コードは、python2.7ベースです。
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import subprocess def call_subprocess(cmd): try: r = subprocess.check_output( cmd, stderr=subprocess.STDOUT ) sys.stdout.write(r+'\n') except OSError as e: sys.stderr.write('file ='+str(e.filename)+'\n') sys.stderr.write('errno='+str(e.errno)+'\n') sys.stderr.write('error='+e.strerror+'\n') return(1) except subprocess.CalledProcessError as e: sys.stderr.write('ret='+str(e.returncode)+'\n') sys.stderr.write('cmd='+str(e.cmd)+'\n') sys.stderr.write('output='+e.output+'\n') return(1) return(0) #test1 a command is success print('<<<<<test1>>>> a command is success.' ) cmd = [ 'echo','hoge hoge' ] ret = call_subprocess(cmd) print('function return = '+str(ret) ) #test2 command is failed print('<<<<<test2>>>> a command is failed.' ) cmd = [ 'cat','hoge hoge' ] ret = call_subprocess(cmd) print('function return = '+str(ret) ) #test3 OS error print('<<<<<test3>>>> OS Error.' ) cmd = [ 'NonexistingFile','hoge hoge' ] ret = call_subprocess(cmd) print('function return = '+str(ret) )