Last active
August 29, 2015 14:22
-
-
Save momijiame/f6aa337bd7028f238c57 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
''' | |
argparse の挙動が Python 2.x と Python 3.x で異なる件について | |
本家のチケット: http://bugs.python.org/issue16308 | |
''' | |
import argparse | |
def _parse(): | |
parser = argparse.ArgumentParser() | |
subparsers = parser.add_subparsers() | |
parser_foo = subparsers.add_parser('foo') | |
parser_foo.set_defaults(func=_exec_foo) | |
# 実行時の引数にサブコマンドの 'foo' がない場合: | |
# Python 2.x ではここで sys.exit() になる | |
# Python 3.x ではそのままスルーする | |
return parser.parse_args() | |
def _exec_foo(args): | |
print('Hello, World!') | |
def _exec(args): | |
# Python 3.x ではそのままここまで突っ走ってしまう | |
# 結果として Namespace#func() がないので例外になる | |
args.func(args) | |
def main(): | |
args = _parse() | |
_exec(args) | |
if __name__ == '__main__': | |
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
''' | |
argparse の挙動が Python 2.x と Python 3.x で異なる件について (バージョンニュートラル版) | |
本家のチケット: http://bugs.python.org/issue16308 | |
''' | |
import sys | |
import argparse | |
def _parse(): | |
parser = argparse.ArgumentParser() | |
subparsers = parser.add_subparsers() | |
parser_foo = subparsers.add_parser('foo') | |
parser_foo.set_defaults(func=_exec_foo) | |
args = parser.parse_args() | |
# Python3 ではサブコマンドがなくても ArgumentParser#parse_args() でエラーにならない | |
# その場合 Namespace#func がセットされないのでアトリビュートを確認してエラーメッセージを出す | |
has_func = hasattr(args, 'func') | |
if not has_func: | |
parser.error('too few arguments') | |
sys.exit(1) | |
return args | |
def _exec_foo(args): | |
print('Hello, World!') | |
def _exec(args): | |
args.func(args) | |
def main(): | |
args = _parse() | |
_exec(args) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment