메뉴 닫기

python command line script, 그럼 bash의 PIPE는 ….

bash에서 쉘의 커맨드라인의 결과를 PIPE로 받을 수도 있고, 넘길 수도 있다.
파이썬으로 명령어 스크립트를 작성하는 경우 어떻게 다가갈수 있을까?

bash에서 입력은 stdin, 출력은 stdout, 에러는 stderr로 연결된다.
따라서 파이썬도 sys패키지에 있는 stdin, stdout, stderr를 사용해서 연결한다.

$ cat -n cmd.py

     1  #!/usr/bin/env python
     2  import sys
     3  
     4  while 1:
     5      try:
     6          input = sys.stdin.readline()
     7          if input:
     8              sys.stdout.write('Stdout: %s'%input)
     9              sys.stderr.write('Stderr: %s'%input)
    10      else:
    11              sys.exit()
    12      except:
    13           sys.exit()


 $ ./cmd.py  < cmd.py   >  cmd.out 

Stderr: #!/usr/bin/env python
Stderr: import sys
Stderr: 
Stderr: while 1:
Stderr:     try:
Stderr:         input = sys.stdin.readline()
Stderr:         if input:
Stderr:             sys.stdout.write('Stdout: %s'%input)
Stderr:             sys.stderr.write('Stderr: %s'%input)
Stderr:     else:
Stderr:             sys.exit()
Stderr:     except:
Stderr:          sys.exit()


$ cat cmd.out

Stdout: #!/usr/bin/env python
Stdout: import sys
Stdout: 
Stdout: while 1:
Stdout:     try:
Stdout:         input = sys.stdin.readline()
Stdout:         if input:
Stdout:             sys.stdout.write('Stdout: %s'%input)
Stdout:             sys.stderr.write('Stderr: %s'%input)
Stdout:     else:
Stdout:             sys.exit()
Stdout:     except:
Stdout:          sys.exit()

입력파일이나 출력파일을 지정하고자 할 경우는 getopt 패키지를 통해 명령어 옵션인 argv와 argc를 받아들여 입력파일과 출력파일이 설정값으로 들어오는지 확인하고 없을 경우 디폴트값을 stdin, stdout으로 맞춰준다.

$ cat cmd2.py

#!/usr/bin/python

import sys, getopt

def main(argv):
    inputfile = ''
    outputfile = ''
    try:
        opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
    except getopt.GetoptError:
        print 'cmd2.py -i  -o '
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'cmd2.py -i  -o '
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg

    if inputfile :
        fi = open(inputfile, 'r')
    else:
        fi = sys.stdin
    if outputfile : 
        fo = open(outputfile, 'w')
    else:
        fo = sys.stdout

    while 1:
        try:
            input = fi.readline()
            if input:
                fo.write('Stdout: %s'%input)
                sys.stderr.write('Stderr: %s'%input)
            else:
                fi.close()
                fo.close()
                sys.exit()
        except:
            fi.close()
            fo.close()
            sys.exit()

if __name__ == "__main__":
   main(sys.argv[1:])

bash의 PIPE를 지원하는 파이썬으로 스크립트를 작성할 경우 가장 기본적인 스크립트 형태이다.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x