optparse模塊爲內置的第三方模塊,實現相似sys.argv的功能,但更加方便好用。python
# -*- coding:utf-8 -*- __author__ = 'Qiushi Huang' import optparse # sys.argv的功能相似 # python ftp_client.py -h 192.168.22.33 -p 8091 # user: # password class FTPClient(object): """ftp客戶端""" def __init__(self): parser = optparse.OptionParser() parser.add_option("-s", "--server", dest="server", help="ftp server ip_addr") parser.add_option("-P", "--port", type="int", dest="port", help="ftp server port") parser.add_option("-u", "--username", dest="username", help="username info") parser.add_option("-p", "--password", dest= "password", help= "password info") self.options, self.args = parser.parse_args() print(self.options, self.args) if __name__ == '__main__': client = FTPClient() # 實例化
執行腳本python3 ftp_client.py 1 324,輸出結果以下:this
{'server': None, 'port': None, 'username': None, 'password': None} ['1', '324']
執行腳本python3 ftp_client.py -s 127.0.0.1 -P 3308 -u admin -p admin,輸出結果以下所示:spa
{'server': '127.0.0.1', 'port': 3308, 'username': 'admin', 'password': 'admin'} []
從上面的代碼能夠看到,optparse模塊能夠幫忙完成輸出參數的解析。同時,還能夠用來查看幫助信息,方便客戶執行程序。執行 python3 ftp_client.py -h,輸出幫助信息以下:code
Usage: ftp_client.py [options] Options: -h, --help show this help message and exit -s SERVER, --server=SERVER ftp server ip_addr -P PORT, --port=PORT ftp server port -u USERNAME, --username=USERNAME username info -p PASSWORD, --password=PASSWORD password info
須要注意雖然self.options打印出來的形式是字典,但實際是一個類,不能使用字典的get方法直接取值。server
class FTPClient(object): """ftp客戶端""" def __init__(self): parser = optparse.OptionParser() parser.add_option("-s", "--server", dest="server", help="ftp server ip_addr") parser.add_option("-P", "--port", type="int", dest="port", help="ftp server port") parser.add_option("-u", "--username", dest="username", help="username info") parser.add_option("-p", "--password", dest= "password", help= "password info") self.options, self.args = parser.parse_args() print(self.options, self.args) print(type(self.options), type(self.args))
執行python3 ftp_client.py,輸出結果以下:blog
$ python3 ftp_client.py {'server': None, 'port': None, 'username': None, 'password': None} [] # options <class 'optparse.Values'> <class 'list'> # args