《可愛的Python》讀書筆記(三)

來源:互聯網
上載者:User

標籤:getopt

先用後學,快速獲得體驗,然後尋求理論支援。

小白根據已有的體驗,對PyCDC的軟體需求進行了進一步完善。

將以往驗證想法的代碼,變成可以方便使用的功能,讓它可以重複在不同應用環境中使用。小白想象著自個兒的PyCDC可以像普通的命令列工具一樣來使用。

行者提出“可以使用getopt.getopt()最佳化當前功能函式”


# -*- coding: utf-8 -*-import osimport sysimport getoptCDROM = 'E:\\'def cdWalker(cdrom,cdcfile):    export = ""    for root, dirs, files in os.walk(cdrom):        export += "\n %s;%s;%s" % (root,dirs,files)    open(cdcfile, 'w').write(export)#運行命令列工具的協助提示    def usage():    print('Usage:python %s -e filename' % sys.argv[0])    try:    opts, args = getopt.getopt(sys.argv[1:], 'e:')    #內有輸入參數將顯示協助提示,並退出程式    if len(opts) == 0:        usage()        sys.exit()    for opt, arg in opts:        if opt == '-e':            cdWalker(CDROM, arg)            print("記錄光碟片資訊到 %s" % arg)        else:            usage()            sys.exit()except getopt.GetoptError:    usage()    sys.exit()

運行效果:

C:\>python pycdc.pywUsage:python pycdc.pyw -e filenameC:\>python pycdc.pyw -e test.txt記錄光碟片資訊到 test.txt

查看test.txt內容如下:


 E:\;['EFI', 'images', 'isolinux', '[BOOT]'];['.discinfo', '.treeinfo', 'CentOS_BuildTag', 'EULA', 'GPL', 'RELEASE-NOTES-en-US.html', 'RPM-GPG-KEY-CentOS-6', 'RPM-GPG-KEY-CentOS-Debug-6', 'RPM-GPG-KEY-CentOS-Security-6', 'RPM-GPG-KEY-CentOS-Testing-6', 'TRANS.TBL']

 E:\EFI;['BOOT'];['TRANS.TBL']

 E:1\EFI\BOOT;[];['BOOTX64.conf', 'BOOTX64.efi', 'splash.xpm.gz', 'TRANS.TBL']

 E:\images;['pxeboot'];['efiboot.img', 'efidisk.img', 'install.img', 'TRANS.TBL']

 E:\images\pxeboot;[];['initrd.img', 'TRANS.TBL', 'vmlinuz']

 E:\isolinux;[];['boot.cat', 'boot.msg', 'grub.conf', 'initrd.img', 'isolinux.bin', 'isolinux.cfg', 'memtest', 'splash.jpg', 'TRANS.TBL', 'vesamenu.c32', 'vmlinuz']

 E:\[BOOT];[];['1-Boot-NoEmul.img', '2-Boot-NoEmul.img']


小白雖然不是非常明白getopt的使用,也還是依葫蘆畫瓢寫了出來,基本實現了想要的功能。


總結:今天學習了使用簡單的getopt實現基本的命令列工具,使用了try...except處理異常,使得程式變得更方便使用

《可愛的Python》讀書筆記(三)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.