紀錄一下Python中如何使用getopt, random的使用
1. getopt: 讓指令後面可以接像bash一樣的參數
import getopt import sys try: opts,args = getopt.getopt(sys.argv[1:],"ri:d:") except getopt.GetoptError as err: print str(err) sys.exit(2) for value,parameter in opts: if value=='-r': #do something elif value=='-i': #do something print value, parameter elif value =='-d': #do something print value, parameter
2. getopt注意事項: |- getopt.getopt(sys.argv[1:],"ri:d:") -> 又冒號表示後面皆參數ex:python exec.py -o file_name |- 沒冒號表示後面不帶參數
3. random的使用範例:
>>> random.random() # Random float x, 0.0 <= x < 1.0 0.37444887175646646 >>> random.uniform(1, 10) # Random float x, 1.0 <= x < 10.0 1.1800146073117523 >>> random.randint(1, 10) # Integer from 1 to 10, endpoints included 7 >>> random.randrange(0, 101, 2) # Even integer from 0 to 100 26 >>> random.choice('abcdefghij') # Choose a random element 'c' >>> items = [1, 2, 3, 4, 5, 6, 7] >>> random.shuffle(items) >>> items [7, 3, 2, 5, 6, 4, 1] >>> random.sample([1, 2, 3, 4, 5], 3) # Choose 3 elements [4, 1, 5]
參考Offical Website
沒有留言:
張貼留言