2017년/Python

파이썬 cmd 모듈

위지원 2017. 9. 15. 00:31

cmd모듈이란?


Support for line-oriented command interpreters


라고 홈페이지에서는 소개해주고 있다. 라인 지향이란 무엇일까? 이제부터 알아보자

일단 설명만 주구장창 읽어보니 모르겠어서 무작정 예제를 실행해보았다 .
아하 '뭘뭘해줘 이만큼'라고 명명함과동시에 파라미터를 넘기는 식으로 함수를 실행해주는 것 같다.

여러가지 메서드가 있는데 중요한걸 알아보자

일단 cmdloop를 통해 계속해서 명령문을 받아드릴 수 있도록 하는게  while문을 대체할 수 있을 것같다.


Cmd.cmdloop(intro=None)

Repeatedly issue a prompt, accept input, parse an initial prefix off the received input, and dispatch to action methods, passing them the remainder of the line as argument.

The optional argument is a banner or intro string to be issued before the first prompt (this overrides the intro class attribute) [생략..]


또 사이트의 예제에 보면 아래와 같이 되어있다. self,arg는 기본인자로 아래의 형태가 기본 형태이다.

  def do_forward(self, arg):
        'Move the turtle forward by the specified distance:  FORWARD 10' #help forward를 치면 출력될 문구이다
        forward(*parse(arg)) 이 문구를 치면 실행될 함수이다.

아주아주 간단하게 코드를 짜봣다 사용방법은 쉬워서 어려운게 없당 ㅎㅎ


import cmd


class my(cmd.Cmd):

    intro = " Hello "

    prompt = " (mdp) "

    file= None



    def do_hello(self,arg):

        'print Hello~'

        self.hello(arg)


    def do_name(self,arg):

        'print name'

        self.name()


    def do_job(self,arg):

        'print job'

        self.job()


    def hello(self,arg):

        print('Hello~',arg)


    def name(self):

        print('weejiwon')


    def job(self):

        print('College student ')


my().cmdloop()



weejw@weejwPC:~/observer$ python3 my.py 

 Hello 

 (mdp) ?


Documented commands (type help <topic>):

========================================

hello  help  job  name


 (mdp) help hello

print Hello~

 (mdp) hello weejiwon

Hello~ weejiwon

 (mdp) help job

print job

 (mdp) job

College student 

 (mdp) help name

print name

 (mdp) name

weejiwon

 (mdp)