언어&플랫폼/python 2013. 12. 9. 15:46

#!/usr/bin/python
import shlex
import subprocess as sub

def excute(self, command):
            try:
                p = sub.Popen(shlex.split(command),stdout=sub.PIPE,stderr=sub.PIPE)
                output, errors = p.communicate()
                return output.strip('\r\n'), errors
            except (ValueError, KeyError, TypeError):
                return -1, -1


만약 명령어가 제대로 실행 되었다면 
     output에 결과가, errors엔 ''
제대로 실행 되지 않았다면,

     output에 ''가, errors엔 잘 못 실행된 내용이 들어온다(예를들면 명령어를 

     잘못 써서 헬프페이지가 올때 그 값은 errors에 들어온다)


try 에 걸린다면 -1, -1이 들어온다.





1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/python
#cmd_sub.py
 
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,

os 모듈을 이용해서 쉘 명령을 실행시켜 출력하기.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/python
#cmd_sub.py
 
import subprocess
 
def execute(cmd) :
    fd = subprocess.Popen(cmd, shell=True,<br>
            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,

subprocess 모듈을 이용해서 쉘 명령을 실행시켜 출력하기.


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


[참고 1] os.popen3
[참고 2] subprocess.Popen
[참고 3] replace os.popen to subprocess


[펌]  - http://gentooboy.tistory.com/72

'언어&플랫폼 > python' 카테고리의 다른 글

[python] dictionary 에 dictionary 붙이기  (0) 2013.12.18
[python] 띄어쓰기 제거  (0) 2013.12.10
[python] json decode  (0) 2013.12.10
Tutorial  (0) 2013.12.10
[python] 로컬 ip 얻기  (0) 2013.11.22
posted by cozyboy
: