日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
用Plumbum開發(fā)Python命令行工具

摘要:本文翻譯自 Python Plumbum 開源庫(kù)的官方文檔 Plumbum CLI 部分,主要介紹如何使用 Plumbum CLI 工具包來開發(fā) Python 命令行應(yīng)用程序,這是一個(gè)非常 Pythonic、容易使用、功能強(qiáng)大的工具包,非常值得廣大 Python 程序員掌握并使用。

創(chuàng)新互聯(lián)公司從2013年開始,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目網(wǎng)站設(shè)計(jì)制作、網(wǎng)站制作網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元蘭坪做網(wǎng)站,已為上家服務(wù),為蘭坪各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220

輕松執(zhí)行程序的另一方面是輕松編寫 CLI 程序。Python 腳本一般使用 optparse 或者***的 argparse 及其衍生品來開發(fā)命令行工具,但是所有這些表現(xiàn)力有限,而且非常不直觀(甚至不夠 Pythonic)。Plumbum 的 CLI 工具包提供了一個(gè)程序化的方法來構(gòu)建命令行應(yīng)用程序,不需要?jiǎng)?chuàng)建一個(gè)解析器對(duì)象,然后填充一系列“選項(xiàng)”,該 CLI 工具包使用內(nèi)省機(jī)制將這些原語(yǔ)轉(zhuǎn)義成 Pythonic 結(jié)構(gòu)。

總體來看,Plumbum CLI 應(yīng)用程序是一個(gè)繼承自 plumbum.cli.Application 的類。這些類定義了一個(gè) main() 方法,并且可選地公開出方法和屬性來作為命令行的選項(xiàng)。這些選項(xiàng)可能需要參數(shù),而任何剩余的位置參數(shù)會(huì)根據(jù) main 函數(shù)的聲明來將其賦予 main 方法。一個(gè)簡(jiǎn)單的 CLI 應(yīng)用程序看起來像如下這樣:

 
 
 
  1. from plumbum import cli
  2.  
  3. class MyApp(cli.Application):
  4. verbose = cli.Flag(["v", "verbose"], help = "If given, I will be very talkative")
  5.  
  6. def main(self, filename):
  7. print("I will now read {0}".format(filename))
  8. if self.verbose:
  9. print("Yadda " * 200)
  10.  
  11. if __name__ == "__main__":
  12. MyApp.run()

你可以運(yùn)行該程序:

 
 
 
  1. $ python example.py foo
  2. I will now read foo
  3.  
  4. $ python example.py --help
  5. example.py v1.0
  6.  
  7. Usage: example.py [SWITCHES] filename
  8. Meta-switches:
  9. -h, --help Prints this help message and quits
  10. --version Prints the program's version and quits
  11.  
  12. Switches:
  13. -v, --verbose If given, I will be very talkative

到現(xiàn)在為止,你只看到了非常基本的使用。我們現(xiàn)在開始探索該庫(kù)。

新版本 1.6.1: 你可以直接運(yùn)行應(yīng)用程序 MyApp(),不需要參數(shù),也不需要調(diào)用 .main()。

應(yīng)用程序

Application 類是你的應(yīng)用程序的“容器”,該“容器”由一個(gè)你需要實(shí)現(xiàn)的main()方法和任何數(shù)量公開選項(xiàng)函數(shù)和屬性。你的應(yīng)用程序的入口是類方法 run,該方法實(shí)例化你的類、解析參數(shù)、調(diào)用所有的選項(xiàng)函數(shù),然后使用給的位置參數(shù)來調(diào)用main()函數(shù)。為了從命令行運(yùn)行你的應(yīng)用程序,你所要做的是:

 
 
 
  1. if __name__ == "__main__":
  2. MyApp.run()

除了 run()main(),Application 類還公開了兩個(gè)內(nèi)置的選項(xiàng)函數(shù):help()version(),分別用于顯示幫助和程序的版本。默認(rèn)情況下,--hep-h 會(huì)調(diào)用 help(),--version-v 會(huì)調(diào)用 version(),這些函數(shù)被調(diào)用后會(huì)顯示相應(yīng)的信息然后退出(沒有處理任何其他選項(xiàng))。

你可以通過定義類屬性來自定義 help()version() 顯示的信息,比如 PROGNAME、 VERSIONDESCRIPTION。舉例:

 
 
 
  1. class MyApp(cli.Application):
  2. PROGNAME = "Foobar"
  3. VERSION = "7.3" 

顏色

新版本 1.6

該庫(kù)也支持終端字符顏色控制。你可以直接將 PROGNAME, VERSIONDESCRIPTION 變?yōu)閹ь伾淖址?。如果你給 PROGNAME 設(shè)置了顏色,你會(huì)得到自定義的程序名字和顏色。使用方法字符串的顏色可以通過設(shè)置 COLOR_USAGE 來生效,不同選項(xiàng)組的顏色可以通過設(shè)置 COLOR_GROUPS 字典來生效。

舉例如下:

 
 
 
  1. class MyApp(cli.Application):
  2. PROGNAME = colors.green
  3. VERSION = colors.blue | "1.0.2"
  4. COLOR_GROUPS = {"Meta-switches" : colors.bold & colors.yellow}
  5. opts = cli.Flag("--ops", help=colors.magenta | "This is help")
 
 
 
  1. SimpleColorCLI.py 1.0.2
  2.  
  3. Usage:
  4. SimpleColorCLI.py [SWITCHES]
  5.  
  6. Meta-switches
  7. -h, --help Prints this help message and quits
  8. --help-all Print help messages of all subcommands and quit
  9. -v, --version Prints the program's version and quits
  10.  
  11. Switches
  12. --ops This is help 

選項(xiàng)函數(shù)

switch 裝飾器是該 CLI 開發(fā)工具包的“靈魂”,它會(huì)公開你的 CLI 應(yīng)用程序的方法來作為 CLI 命令行選項(xiàng),這些方法運(yùn)行通過命令行來調(diào)用。我們測(cè)試下如下應(yīng)用:

 
 
 
  1. class MyApp(cli.Application):
  2. _allow_root = False # provide a default
  3.  
  4. @cli.switch("--log-to-file", str)
  5. def log_to_file(self, filename):
  6. """Sets the file into which logs will be emitted"""
  7. logger.addHandler(FileHandle(filename))
  8.  
  9. @cli.switch(["-r", "--root"])
  10. def allow_as_root(self):
  11. """If given, allow running as root"""
  12. self._allow_root = True
  13.  
  14. def main(self):
  15. if os.geteuid() == 0 and not self._allow_root:
  16. raise ValueError("cannot run as root")

當(dāng)程序運(yùn)行時(shí),選項(xiàng)函數(shù)通過相應(yīng)的參數(shù)被調(diào)用。比如,$ ./myapp.py --log-to-file=/tmp/log 將被轉(zhuǎn)化成調(diào)用 app.log_to_file("/tmp/log")。在選項(xiàng)函數(shù)被執(zhí)行后,程序的控制權(quán)會(huì)被傳遞到 main 方法。

注意

方法的文檔字符串和參數(shù)名字會(huì)被用來渲染幫助信息,盡量保持你的代碼 DRY。

autoswitch 可以從函數(shù)名字中推斷出選項(xiàng)的名稱,舉例如下:

  
  
  
  1. @cli.autoswitch(str)
  2. def log_to_file(self, filename):
  3. pass

這會(huì)將選項(xiàng)函數(shù)和 --log-to-file 綁定。

選項(xiàng)參數(shù)

如上面例子所示,選項(xiàng)函數(shù)可能沒有參數(shù)(不包括 self)或者有一個(gè)參數(shù)。如果選項(xiàng)函數(shù)接受一個(gè)參數(shù),必須指明該參數(shù)的類型。如果你不需要特殊的驗(yàn)證,只需傳遞 str,否則,您可能會(huì)傳遞任何類型(或?qū)嶋H上可調(diào)用的任何類型),該類型將接收一個(gè)字符串并將其轉(zhuǎn)換為有意義的對(duì)象。如果轉(zhuǎn)換是不可行的,那么會(huì)拋出 TypeError 或者 ValueError 異常。

舉例:

 
 
 
  1. class MyApp(cli.Application):
  2. _port = 8080
  3.  
  4. @cli.switch(["-p"], int)
  5. def server_port(self, port):
  6. self._port = port
  7.  
  8. def main(self):
  9. print(self._port)
 
 
 
  1. $ ./example.py -p 17
  2. 17
  3. $ ./example.py -p foo
  4. Argument of -p expected to be , not 'foo':
  5. ValueError("invalid literal for int() with base 10: 'foo'",)

工具包包含兩個(gè)額外的“類型”(或者是是驗(yàn)證器):RangeSetRange 指定一個(gè)最小值和***值,限定一個(gè)整數(shù)在該范圍內(nèi)(閉區(qū)間)。Set 指定一組允許的值,并且期望參數(shù)匹配這些值中的一個(gè)。示例如下:

 
 
 
  1. class MyApp(cli.Application):
  2. _port = 8080
  3. _mode = "TCP"
  4.  
  5. @cli.switch("-p", cli.Range(1024,65535))
  6. def server_port(self, port):
  7. self._port = port
  8.  
  9. @cli.switch("-m", cli.Set("TCP", "UDP", case_sensitive = False))
  10. def server_mode(self, mode):
  11. self._mode = mode
  12.  
  13. def main(self):
  14. print(self._port, self._mode)
 
 
 
  1. $ ./example.py -p 17
  2. Argument of -p expected to be [1024..65535], not '17':
  3. ValueError('Not in range [1024..65535]',)
  4. $ ./example.py -m foo
  5. Argument of -m expected to be Set('udp', 'tcp'), not 'foo':
  6. ValueError("Expected one of ['UDP', 'TCP']",)

注意 工具包中還有其他有用的驗(yàn)證器:ExistingFile(確保給定的參數(shù)是一個(gè)存在的文件),ExistingDirectory(確保給定的參數(shù)是一個(gè)存在的目錄),NonexistentPath(確保給定的參數(shù)是一個(gè)不存在的路徑)。所有這些將參數(shù)轉(zhuǎn)換為本地路徑。

可重復(fù)的選項(xiàng)

很多時(shí)候,你需要在同一個(gè)命令行中多次指定某個(gè)選項(xiàng)。比如,在 gcc 中,你可能使用 -I 參數(shù)來引入多個(gè)目錄。默認(rèn)情況下,選項(xiàng)只能指定一次,除非你給 switch 裝飾器傳遞 list = True 參數(shù)。

 
 
 
  1. class MyApp(cli.Application):
  2. _dirs = []
  3.  
  4. @cli.switch("-I", str, list = True)
  5. def include_dirs(self, dirs):
  6. self._dirs = dirs
  7.  
  8. def main(self):
  9. print(self._dirs)
 
 
 
  1. $ ./example.py -I/foo/bar -I/usr/include
  2. ['/foo/bar', '/usr/include']

注意 選項(xiàng)函數(shù)只被調(diào)用一次,它的參數(shù)將會(huì)變成一個(gè)列表。

強(qiáng)制的選項(xiàng)

如果某個(gè)選項(xiàng)是必須的,你可以給 switch 裝飾器傳遞 mandatory = True 來實(shí)現(xiàn)。這樣的話,如果用戶不指定該選項(xiàng),那么程序是無法運(yùn)行的。

選項(xiàng)依賴

很多時(shí)候,一個(gè)選項(xiàng)的出現(xiàn)依賴另一個(gè)選項(xiàng),比如,如果不給定 -y 選項(xiàng),那么 -x 選項(xiàng)是無法給定的。這種限制可以通過給 switch 裝飾器傳遞 requires 參數(shù)來實(shí)現(xiàn),該參數(shù)是一個(gè)當(dāng)前選項(xiàng)所依賴的選項(xiàng)名稱列表。如果不指定某個(gè)選項(xiàng)所依賴的其他選項(xiàng),那么用戶是無法運(yùn)行程序的。

 
 
 
  1. class MyApp(cli.Application):
  2. @cli.switch("--log-to-file", str)
  3. def log_to_file(self, filename):
  4. logger.addHandler(logging.FileHandler(filename))
  5.  
  6. @cli.switch("--verbose", requires = ["--log-to-file"])
  7. def verbose(self):
  8. logger.setLevel(logging.DEBUG)
 
 
 
  1. $ ./example --verbose
  2. Given --verbose, the following are missing ['log-to-file']

警告 選項(xiàng)函數(shù)的調(diào)用順序和命令行指定的選項(xiàng)的順序是一致的。目前不支持在程序運(yùn)行時(shí)計(jì)算選項(xiàng)函數(shù)調(diào)用的拓?fù)漤樞?,但是將來?huì)改進(jìn)。

選項(xiàng)互斥

有些選項(xiàng)依賴其他選項(xiàng),但是有些選項(xiàng)是和其他選項(xiàng)互斥的。比如,--verbose--terse 同時(shí)存在是不合理的。為此,你可以給 switch 裝飾器指定 excludes 列表來實(shí)現(xiàn)。

 
 
 
  1. class MyApp(cli.Application):
  2. @cli.switch("--log-to-file", str)
  3. def log_to_file(self, filename):
  4. logger.addHandler(logging.FileHandler(filename))
  5.  
  6. @cli.switch("--verbose", requires = ["--log-to-file"], excludes = ["--terse"])
  7. def verbose(self):
  8. logger.setLevel(logging.DEBUG)
  9.  
  10. @cli.switch("--terse", requires = ["--log-to-file"], excludes = ["--verbose"])
  11. def terse(self):
  12. logger.setLevel(logging.WARNING)
 
 
 
  1. $ ./example --log-to-file=log.txt --verbose --terse
  2. Given --verbose, the following are invalid ['--terse'] 

選項(xiàng)分組

如果你希望在幫助信息中將某些選項(xiàng)組合在一起,你可以給 switch 裝飾器指定 group = "Group Name", Group Name 可以是任意字符串。當(dāng)顯示幫助信息的時(shí)候,所有屬于同一個(gè)組的選項(xiàng)會(huì)被聚合在一起。注意,分組不影響選項(xiàng)的處理,但是可以增強(qiáng)幫助信息的可讀性。

選項(xiàng)屬性

很多時(shí)候只需要將選項(xiàng)的參數(shù)存儲(chǔ)到類的屬性中,或者當(dāng)某個(gè)屬性給定后設(shè)置一個(gè)標(biāo)志。為此,工具包提供了 SwitchAttr,這是一個(gè)數(shù)據(jù)描述符,用來存儲(chǔ)參數(shù)。 該工具包還提供了兩個(gè)額外的 SwitchAttr:Flag(如果選項(xiàng)給定后,會(huì)給其賦予默認(rèn)值)和 CountOf (某個(gè)選項(xiàng)出現(xiàn)的次數(shù))。

 
 
 
  1. class MyApp(cli.Application):
  2. log_file = cli.SwitchAttr("--log-file", str, default = None)
  3. enable_logging = cli.Flag("--no-log", default = True)
  4. verbosity_level = cli.CountOf("-v")
  5.  
  6. def main(self):
  7. print(self.log_file, self.enable_logging, self.verbosity_level)
 
 
 
  1. $ ./example.py -v --log-file=log.txt -v --no-log -vvv
  2. log.txt False 5 

環(huán)境變量

新版本 1.6

你可以使用 envname 參數(shù)將環(huán)境變量作為 SwitchAttr 的輸入。舉例如下:

 
 
 
  1. class MyApp(cli.Application):
  2. log_file = cli.SwitchAttr("--log-file", str, envname="MY_LOG_FILE")
  3.  
  4. def main(self):
  5. print(self.log_file)
 
 
 
  1. $ MY_LOG_FILE=this.log ./example.py
  2. this.log

在命令行給定變量值會(huì)覆蓋相同環(huán)境變量的值。

Main

一旦當(dāng)所有命令行參數(shù)被處理后 ,main() 方法會(huì)獲取程序的控制,并且可以有任意數(shù)量的位置參數(shù),比如,在 cp -r /foo /bar 中, /foo/bar 是位置參數(shù)。程序接受位置參數(shù)的數(shù)量依賴于 main() 函數(shù)的聲明:如果 main 方法有 5 個(gè)參數(shù),2 個(gè)是有默認(rèn)值的,那么用戶最少需要提供 3 個(gè)位置參數(shù)并且總數(shù)量不能多于 5 個(gè)。如果 main 方法的聲明中使用的是可變參數(shù)(*args),那么位置參數(shù)的個(gè)數(shù)是沒有限制的。

 
 
 
  1. class MyApp(cli.Application):
  2. def main(self, src, dst, mode = "normal"):
  3. print(src, dst, mode)
 
 
 
  1. $ ./example.py /foo /bar
  2. /foo /bar normal
  3. $ ./example.py /foo /bar spam
  4. /foo /bar spam
  5. $ ./example.py /foo
  6. Expected at least 2 positional arguments, got ['/foo']
  7. $ ./example.py /foo /bar spam bacon
  8. Expected at most 3 positional arguments, got ['/foo', '/bar', 'spam', 'bacon']

注意 該方法的聲明也用于生成幫助信息,例如:

  
  
  
  1. Usage: [SWITCHES] src dst [mode='normal']

使用可變參數(shù):

 
 
 
  1. class MyApp(cli.Application):
  2. def main(self, src, dst, *eggs):
  3. print(src, dst, eggs)
 
 
 
  1. $ ./example.py a b c d
  2. a b ('c', 'd')
  3. $ ./example.py --help
  4. Usage: [SWITCHES] src dst eggs...
  5. Meta-switches:
  6. -h, --help Prints this help message and quits
  7. -v, --version Prints the program's version and quits 

位置驗(yàn)證

新版本 1.6

你可以使用 cli.positional 裝飾器提供的驗(yàn)證器來驗(yàn)證位置參數(shù)。只需在裝飾器中傳遞與 main 函數(shù)中的相匹配的驗(yàn)證器即可。例如:

 
 
 
  1. class MyApp(cli.Application):
  2. @cli.positional(cli.ExistingFile, cli.NonexistentPath)
  3. def main(self, infile, *outfiles):
  4. "infile is a path, outfiles are a list of paths, proper errors are given"

如果你的程序只在 Python 3 中運(yùn)行,你可以使用注解來指定驗(yàn)證器,例如:

 
 
 
  1. class MyApp(cli.Application):
  2. def main(self, infile : cli.ExistingFile, *outfiles : cli.NonexistentPath):
  3. "Identical to above MyApp"

如果 positional 裝飾器存在,那么注解會(huì)被忽略。

子命令

新版本 1.1

隨著 CLI 應(yīng)用程序的擴(kuò)展,功能變的越來越多,一個(gè)通常的做法是將其邏輯分成多個(gè)子應(yīng)用(或者子命令)。一個(gè)典型的例子是版本控制系統(tǒng),比如 git,git 是根命令,在這之下的子命令比如 commit 或者 push 是嵌套的。git 甚至支持命令別名,這運(yùn)行用戶自己創(chuàng)建一些子命令。Plumbum 寫類似這樣的程序是很輕松的。

在我們開始了解代碼之前,先強(qiáng)調(diào)兩件事情:

  • 在 Plumbum 中,每個(gè)子命令都是一個(gè)完整的 cli.Application 應(yīng)用,你可以單獨(dú)執(zhí)行它,或者從所謂的根命令中分離出來。當(dāng)應(yīng)用程序單獨(dú)執(zhí)行是,它的父屬性是 None,當(dāng)以子命令運(yùn)行時(shí),它的父屬性指向父應(yīng)用程序。同樣,當(dāng)父應(yīng)用使用子命令執(zhí)行時(shí),它的內(nèi)嵌命令被設(shè)置成內(nèi)嵌應(yīng)用。
  • 每個(gè)子命令只負(fù)責(zé)它自己的選項(xiàng)參數(shù)(直到下一個(gè)子命令)。這允許應(yīng)用在內(nèi)嵌應(yīng)用調(diào)用之前來處理它自己的選項(xiàng)和位置參數(shù)。例如 git --foo=bar spam push origin --tags:根應(yīng)用 git 負(fù)責(zé)選項(xiàng) --foo 和位置選項(xiàng) spam ,內(nèi)嵌應(yīng)用 push 負(fù)責(zé)在它之后的參數(shù)。從理論上講,你可以將多個(gè)子應(yīng)用程序嵌套到另一個(gè)應(yīng)用程序中,但在實(shí)踐中,通常嵌套層級(jí)只有一層。

這是一個(gè)模仿版本控制系統(tǒng)的例子 geet。我們有一個(gè)根應(yīng)用 Geet ,它有兩個(gè)子命令 GeetCommitGeetPush:這兩個(gè)子命令通過 subcommand 裝飾器來將其附加到根應(yīng)用。

 
 
 
  1. class Geet(cli.Application):
  2. """The l33t version control"""
  3. VERSION = "1.7.2"
  4.  
  5. def main(self, *args):
  6. if args:
  7. print("Unknown command {0!r}".format(args[0]))
  8. return 1 # error exit code
  9. if not self.nested_command: # will be ``None`` if no sub-command follows
  10. print("No command given")
  11. return 1 # error exit code
  12.  
  13. @Geet.subcommand("commit") # attach 'geet commit'
  14. class GeetCommit(cli.Application):
  15. """creates a new commit in the current branch"""
  16.  
  17. auto_add = cli.Flag("-a", help = "automatically add changed files")
  18. message = cli.SwitchAttr("-m", str, mandatory = True, help = "sets the commit message")
  19.  
  20. def main(self):
  21. print("doing the commit...")
  22.  
  23. @Geet.subcommand("push") # attach 'geet push'
  24. class GeetPush(cli.Application):
  25. """pushes the current local branch to the remote one"""
  26. def main(self, remote, branch = None):
  27. print("doing the push...")
  28.  
  29. if __name__ == "__main__":
  30. Geet.run()

注意

  • 由于 GeetCommit 也是一個(gè) cli.Application,因此你可以直接調(diào)用 GeetCommit.run() (這在應(yīng)用的上下文是合理的)
  • 你也可以不用裝飾器而使用 subcommand 方法來附加子命令:Geet.subcommand("push", GeetPush)

以下是運(yùn)行該應(yīng)用程序的示例:

 
 
 
  1. $ python geet.py --help
  2. geet v1.7.2
  3. The l33t version control
  4.  
  5. Usage: geet.py [SWITCHES] [SUBCOMMAND [SWITCHES]] args...
  6. Meta-switches:
  7. -h, --help Prints this help message and quits
  8. -v, --version Prints the program's version and quits
  9.  
  10. Subcommands:
  11. commit creates a new commit in the current branch; see
  12. 'geet commit --help' for more info
  13. push pushes the current local branch to the remote
  14. one; see 'geet push --help' for more info
  15.  
  16. $ python geet.py commit --help
  17. geet commit v1.7.2
  18. creates a new commit in the current branch
  19.  
  20. Usage: geet commit [SWITCHES]
  21. Meta-switches:
  22. -h, --help Prints this help message and quits
  23. -v, --version Prints the program's version and quits
  24.  
  25. Switches:
  26. -a automatically add changed files
  27. -m VALUE:str sets the commit message; required
  28.  
  29. $ python geet.py commit -m "foo"
  30. doing the commit... 

配置解析器

應(yīng)用程序的另一個(gè)常見的功能是配置文件解析器,解析后臺(tái) INI 配置文件:Config (或者 ConfigINI)。使用示例:

 
 
 
  1. from plumbum import cli
  2.  
  3. with cli.Config('~/.myapp_rc') as conf:
  4. one = conf.get('one', '1')
  5. two = conf.get('two', '2')

如果配置文件不存在,那么將會(huì)以當(dāng)前的 key 和默認(rèn)的 value 來創(chuàng)建一個(gè)配置文件,在調(diào)用 .get 方法時(shí)會(huì)得到默認(rèn)值,當(dāng)上下文管理器存在時(shí),文件會(huì)被創(chuàng)建。如果配置文件存在,那么該文件將會(huì)被讀取并且沒有任何改變。你也可以使用 [] 語(yǔ)法來強(qiáng)制設(shè)置一個(gè)值或者當(dāng)變量不存在時(shí)獲取到一個(gè) ValueError。如果你想避免上下文管理器,你也可以使用 .read.write。

ini 解析器默認(rèn)使用 [DEFAULT] 段,就像 Python 的 ConfigParser。如果你想使用一個(gè)不同的段,只需要在 key 中通過 . 將段和標(biāo)題分隔開。比如 conf['section.item'] 會(huì)將 item 放置在 [section] 下。所有存儲(chǔ)在 ConfigINI 中的條目會(huì)被轉(zhuǎn)化成 str,str 是經(jīng)常返回的。

終端實(shí)用程序

plumbum.cli.terminal 中有多個(gè)終端實(shí)用程序,用來幫助制作終端應(yīng)用程序。

get_terminal_size(default=(80,25)) 允許跨平臺(tái)訪問終端屏幕大小,返回值是一個(gè)元組 (width, height)。還有幾個(gè)方法可以用來詢問用戶輸入,比如 readline, ask, chooseprompt 都是可用的。

Progress(iterator) 可以使你快速地從迭代器來創(chuàng)建一個(gè)進(jìn)度條。簡(jiǎn)單地打包一個(gè) slow 迭代器并迭代就會(huì)生成一個(gè)不錯(cuò)的基于用戶屏幕寬度的文本進(jìn)度條,同時(shí)會(huì)顯示剩余時(shí)間。如果你想給 fast 迭代器創(chuàng)建一個(gè)進(jìn)度條,并且在循環(huán)中包含代碼,那么請(qǐng)使用 Progress.wrap 或者 Progress.range。例如:

 
 
 
  1. for i in Progress.range(10):
  2. time.sleep(1)

如果在終端中有其他輸出,但是仍然需要一個(gè)進(jìn)度條,請(qǐng)傳遞 has_output=True 參數(shù)來禁止進(jìn)度條清除掉歷史輸出。

plumbum.cli.image 中提供了一個(gè)命令行繪圖器(Image)。它可以繪制一個(gè)類似 PIL 的圖像:

 
 
 
  1. Image().show_pil(im)

Image 構(gòu)造函數(shù)接受一個(gè)可選的 size 參數(shù)(如果是 None,那么默認(rèn)是當(dāng)前終端大小)和一個(gè)字符比例,該比例來自當(dāng)前字符的高度和寬度的度量,默認(rèn)值是 2.45。如果設(shè)置為 None,ratio 將會(huì)被忽略,圖像不再被限制成比例縮放。要直接繪制一個(gè)圖像,show 需要一個(gè)文件名和一對(duì)參數(shù)。show_pilshow_pil_double 方法直接接受一個(gè) PIL-like 對(duì)象。為了從命令行繪制圖像,該模塊可以直接被運(yùn)行:python -m plumbum.cli.image myimage.png。

要獲取幫助列表和更多的信息請(qǐng)參見 api docs。

請(qǐng)參閱

  • filecopy.py 示例
  • geet.py - 一個(gè)可運(yùn)行的使用子命令的示例
  • RPyC 已經(jīng)將基于 bash 的編譯腳本換成了 Plumbum CLI。這是多么簡(jiǎn)短和具有可讀性
  • 一篇博客,講述 CLI 模塊的理論 

新聞名稱:用Plumbum開發(fā)Python命令行工具
標(biāo)題鏈接:http://m.5511xx.com/article/cdshooi.html