getopt 是一個python模塊, 處理命令行參數的,和sys.argv是一樣的功能, 這個功能和c語言處理命令行參數的功能和函數是一樣的, 例如你在命令行里邊是這樣運行的: python test_getopy.py -i:127.0.0.1 -p:8888 或者python test_getopt.py --ip=127.0.01 --port=8888, getopt模塊將幫你處理這些參數,下邊是一些常用的場景,希望能幫到你。
python 文件名字: test_getopt.py
python 文件執行參數:python test_getopt.py -p:8888 -ip:127.0.0.1
test_getopt.py 代碼:
#!/usr/bin/env python import getopt import sys def main(): """ python test_getopt.py -i:127.0.0.1 -p:8888 """ options, args = getopt.getopt(sys.argv[1:], 'p:i:') for name, value in options: if name in ('-i'): # value is 127.0.0.1 print ("value: {0}".format(value)) if name in ('-p'): # value is 8888 print ("value: {0}".format(value)) if __name__ == "__main__": main()
如果你是這樣運行的代碼:python test_getopt.py -i:127.0.0.1 -p:8888. 那么在上邊的代碼中-i的name值就是127.0.0.1 -p的name值就是8888,getopt.getopt(sys.argv[1:], 'p:i:') 第一個參數就是取文件名后邊的參數, 第二個參數‘p:i:’ 就是你命令行的參數是帶一個'-'符號的, ':' 符號是你的參數必須有值:例如:-i:127.0.0.1.
你也可以加入-h選項,當別人輸入python test_getopt.py -h 的時候會看到help的信息。代碼如下
#!/usr/bin/env python import getopt import sys def usage(): print ("==========") print ("Usage:") print (". xxxxxxx") print (". xxxxxxx") print ("==========") def main(): """ python test_getopt.py -h """ options, args = getopt.getopt(sys.argv[1:], 'h') for name, value in options: if name in ('-h'): usage() if __name__ == "__main__": main()
上邊的代碼實例都是參數是帶一個‘-’符號的, 你也可以使用帶‘--’符號的參數, 代碼如下:
#!/usr/bin/env python import getopt import sys def usage(): print ("=======") print ("Usage:") print ("python test_getopt.py -I:127.0.0.1 -p:8888 66 88 or python test_getopt.py --ip=127.0.0.1 --port=8888 66 88") print ("=======") def main(): """ getopt 模塊的用法 """ options, args = getopt.getopt(sys.argv[1:], 'hp:i:', ['help', 'port=', 'ip=']) for name, value in options: if name in ('-h', '--help'): usage() if name in ('-p', '--port'): print ('value: {0}'.format(value)) if name in ('-i', '--ip'): print ('value: {0}'.format(value)) for name in args: # name 的值就是 上邊參數實例里邊的66和88 print ("name: {0}".format(name)) if __name__ == "__main__": main()
轉載於https://blog.csdn.net/qq_34765864/article/details/81368754