Flower in my dev/Python

<PYTHON>[subprocess]

꽃선생 2015. 5. 7. 10:39

파이썬에서 시스템 명령을 실행하는 방법 중에 하나이다.

 

1
2
3
import subprocess
 
subprocess.call('ls -al', shell=True)
cs

 

subprocess를 모듈로 등록하고

 

call을 불러서 사용하면 끝이다.

 

결과를 리턴 받고 싶다면

 

result = subprocess.check_output('명령', shell=True)

 

그리고 result를 가지고 조건을 걸어 사용하면 끝.


==========<<<추가>>>==========


Popen을 사용하는 방법


1
2
3
4
5
import subprocess
 
= subprocess.Popen('ls', stdout=subprocess.PIPE).stdout
 
rs = r.read().strip()
cs


ipython에서 결과




check_output은 마지막 줄바꿈이 되기 때문에 


\n로 split을 하면 리스트의 길이가 하나 늘어나는데


[:-1]로 해결해주면 간단하다.