python:argparse

差分

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

この比較画面へのリンク

両方とも前のリビジョン 前のリビジョン
次のリビジョン
前のリビジョン
python:argparse [2020/02/01 19:49] – [参考文献] ともやん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
行 10: 行 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 directory or file.', type=str)+    parser.add_argument('--exclude', nargs='+', help='exclude directory or file.', type=str)
     return parser.parse_args()     return parser.parse_args()
  
行 16: 行 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> </code>
 +</WRAP>
  
 ===== 実行例 ===== ===== 実行例 =====
-<code>+<WRAP prewrap 100%> 
 +<code powershell>
 $ python args_sample.py $ python args_sample.py
-usage: args_sample.py [-h] [--exclude EXCLUDE] target_dir+</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 args_sample.py: error: the following arguments are required: target_dir
 +</code>
 +</WRAP>
  
 +<WRAP prewrap 100%>
 +<code powershell>
 $ python args_sample.py -h $ python args_sample.py -h
-usage: args_sample.py [-h] [--exclude EXCLUDE] target_dir+</code> 
 +</WRAP> 
 +<WRAP prewrap 100% #result> 
 +<code powershell> 
 +usage: args_sample.py [-h] [--exclude EXCLUDE [EXCLUDE ...]] target_dir
  
 positional arguments: positional arguments:
-  target_dir         target dir.+  target_dir            target dir.
  
 optional arguments: optional arguments:
-  -h, --help         show this help message and exit +  -h, --help            show this help message and exit 
-  --exclude EXCLUDE  exclude directory or file.+  --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>
  
 ===== 参考文献 ===== ===== 参考文献 =====
  • python/argparse.1580554155.txt.gz
  • 最終更新: 2020/02/01 19:49
  • by ともやん