標籤: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》讀書筆記(三)