[系統互動篇] 如何從系統命令列,讀取輸入的參數 - tsungjung411/python-study GitHub Wiki
python get parameter from cmd
傳統方式讀取
import sys
print(sys.argv)
Argparse 教學
用來解析輸入參數的套件,不用在自己去硬刻剖析器
官方範例
- test.py
import argparse parser = argparse.ArgumentParser() parser.parse_args()
- 執行測試
$python test.py --help usage: test.py [-h] optional arguments: -h, --help show this help message and exit
位置參數用法
- 介紹位置參數
import argparse parser = argparse.ArgumentParser() parser.add_argument("echo") args = parser.parse_args() print(args.echo)
如何顯示多行的程式說明?
- test.py
import argparse parser = argparse.ArgumentParser(description=''' This is a sample for argument parser. If you want to show multiple lines, you need to use 'RawTextHelpFormatter' ''', formatter_class=argparse.RawTextHelpFormatter) args = parser.parse_args()
- 執行結果(使用RawTextHelpFormatter)
$ python test.py -h usage: test.py [-h] This is a sample for argument parser. If you want to show multiple lines, you need to use 'RawTextHelpFormatter' optional arguments: -h, --help show this help message and exit
- 執行結果(不使用RawTextHelpFormatter)
$ python test.py -h usage: test.py [-h] This is a sample for argument parser. If you want to show multiple lines, you need to use 'RawTextHelpFormatter' optional arguments: -h, --help show this help message and exit
如何同時允許「短參數(-v)」和「長參數(--verbose)」
- test.py
import argparse parser = argparse.ArgumentParser() parser.add_argument('-v', '--verbose', help="increase output verbosity", action="store_true") print('parser:', parser) args = parser.parse_args() print('args:', args)
- 執行結果
$ python test.py -v $ python test.py --verbose ('parser:', ArgumentParser(prog='test.py', usage=None, description=None, version=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)) ('args:', Namespace(verbose=True))
如何允許未知參數的輸入,以及如何重導指令
- test.py
import argparse parser = argparse.ArgumentParser() parser.add_argument('--verbose', help="increase output verbosity", action="store_true") print('parser:', parser) args, unknown_args = parser.parse_known_args() print('args:', args) print('unknown_args:', unknown_args) import os os.system('echo ' + ' '.join(unknown_args))
- 執行結果
$ python test.py -msg 'hello' -msg 'hi' --message="long message" ('parser:', ArgumentParser(prog='test.py', usage=None, description=None, version=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)) ('args:', Namespace(verbose=False)) ('unknown_args:', ['-msg', 'hello', '-msg', 'hi', '--message=long message']) -msg hello -msg hi --message=long message