python:argparse

差分

このページの2つのバージョン間の差分を表示します。

この比較画面へのリンク

両方とも前のリビジョン 前のリビジョン
次のリビジョン
前のリビジョン
python:argparse [2020/02/01 19:13] – [argparse] ともやんpython:argparse [2020/09/11 16:30] (現在) ともやん
行 1: 行 1:
-====== argparse ======+====== argparse - コマンドライン引数解析 ====== 
 + 
 +===== サンプル ===== 
 +<WRAP prewrap 100% #mincode>
 <code python args_sample.py> <code python args_sample.py>
 #!/usr/bin/env python #!/usr/bin/env python
行 8: 行 11:
     parser = argparse.ArgumentParser()     parser = argparse.ArgumentParser()
     parser.add_argument('target_dir', help='target dir.', type=str)     parser.add_argument('target_dir', help='target dir.', type=str)
-    parser.add_argument('--exclude', help='exclude dir.', type=str)+    parser.add_argument('--exclude', nargs='+', help='exclude directory or file.', type=str)
     return parser.parse_args()     return parser.parse_args()
  
行 14: 行 17:
     args = parse_args()     args = parse_args()
     target_dir = args.target_dir     target_dir = args.target_dir
-    exclude_dir = args.exclude+    exclude_dirs = args.exclude
  
     print(f'target_dir: {target_dir}')     print(f'target_dir: {target_dir}')
-    print(f'exclude_dir: {exclude_dir}')+    print(f'exclude_dirs: {exclude_dirs}')
  
 if __name__ == '__main__': if __name__ == '__main__':
     main()     main()
 +</code>
 +</WRAP>
  
 +===== 実行例 =====
 +<WRAP prewrap 100%>
 +<code powershell>
 +$ python args_sample.py
 +</code>
 +</WRAP>
 +<WRAP prewrap 100% #result>
 +<code powershell>
 +usage: args_sample.py [-h] [--exclude EXCLUDE [EXCLUDE ...]] target_dir
 +args_sample.py: error: the following arguments are required: target_dir
 +</code>
 +</WRAP>
 +
 +<WRAP prewrap 100%>
 +<code powershell>
 +$ python args_sample.py -h
 +</code>
 +</WRAP>
 +<WRAP prewrap 100% #result>
 +<code powershell>
 +usage: args_sample.py [-h] [--exclude EXCLUDE [EXCLUDE ...]] target_dir
 +
 +positional arguments:
 +  target_dir            target dir.
 +
 +optional arguments:
 +  -h, --help            show this help message and exit
 +  --exclude EXCLUDE [EXCLUDE ...]
 +                        exclude directory or file.
 +</code>
 +</WRAP>
 +
 +<WRAP prewrap 100%>
 +<code powershell>
 +$ python args_sample.py / --exclude .git
 +</code>
 +</WRAP>
 +<WRAP prewrap 100% #result>
 +<code powershell>
 +target_dir: /
 +exclude_dirs: ['.git']
 </code> </code>
 +</WRAP>
  
 ===== 参考文献 ===== ===== 参考文献 =====
 [[https://docs.python.org/ja/3/howto/argparse.html|Argparse チュートリアル — Python 3.8.1 ドキュメント]]\\ [[https://docs.python.org/ja/3/howto/argparse.html|Argparse チュートリアル — Python 3.8.1 ドキュメント]]\\
 +[[https://docs.python.org/ja/3/library/argparse.html|argparse --- コマンドラインオプション、引数、サブコマンドのパーサー — Python 3.8.1 ドキュメント]]\\
  
  • python/argparse.1580552023.txt.gz
  • 最終更新: 2020/02/01 19:13
  • by ともやん