- python source code 상에서 bash command 실행하는 방법
- os.system 사용
- 예제
# --------------------------------------------------------------------------------
# os.system 이용하여 명령 실행하기
# --------------------------------------------------------------------------------
"""
os.system
단순한 명령 실행 필요시 사용
결과값
"""
import os
import sys
# 간단한 명령어 사용 example
result = os.system('pwd')
print 'result is : ', result
os.system('ls -al')
# image search module test
os.system(user_cmd)
- import sh 사용
- subprocess 사용
- http://egloos.zum.com/parkmo/v/4184564
- https://docs.python.org/2/library/subprocess.html
- 예제1
##
# --------------------------------------------------------------------------------
# subprocess 이용하여 명령 실행하기
# --------------------------------------------------------------------------------\
import subprocess
# # 단순 실행시 : call() 사용
# subprocess.call('ls -al', shell=True)
#
# # 특정 명령 수행 결과 이용시 : check_output() 사용
# result = subprocess.check_output(user_cmd, shell=True)
# print result
# test
# cmd = 'ls -al > output.txt'
cmd = 'python /home/juce/study/python/test/test_bash.py'
result = subprocess.check_output(cmd, shell=True)
print result - 예제2
import subprocessdef get_search_images(cmd_args):
fd_popen = subprocess.Popen(cmd_args.split(), stdout=subprocess.PIPE).stdout
data = fd_popen.read().strip()
fd_popen.close()
data = data.split('\n')
return data - 위의 코드에서
- 실제로 bash 에서 사용하고 싶은 명령어를 cmd_args 로 string 으로 넘겨주면 된다.
'Python > Examples' 카테고리의 다른 글
| Python | Examples | Math functions (buillt-in), 버림, 반올림, 내림, 올림 (0) | 2016.03.07 |
|---|---|
| Python | Examples | 이미지 파일 binary 로 read 후 web browser 에서 data 받아서 보여주기 (0) | 2016.03.03 |
| Python | Examples | dictionary 에서 key 값만 얻기 (0) | 2016.03.02 |
| Python | Examples | BeautifulSoup | convert NavigableString to string (0) | 2016.03.02 |
| Python | Examples | String to datetime (0) | 2016.03.02 |