0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

シェルスクリプトのオプション解析をpythonに任せる

Last updated at Posted at 2025-05-15
f_process_python_output() {
    parse_args() {
        python3 - "$@" <<'EOF'
import argparse
import sys

parser = argparse.ArgumentParser(prog='hoge.sh', description="ファイル処理スクリプト", add_help=False)
parser.add_argument('--mail-file', required=True, help='対象のファイル名')

try:
    args = parser.parse_args()
except SystemExit as e:
    if e.code == 0:
        # help表示による正常終了
        print("__HELP__")
    sys.exit(e.code)
except argparse.ArgumentError as e:
    print(f"エラー: {e}", file=sys.stderr)
    sys.exit(2)

# 正常な場合だけ変数を出力
print(f'MAIL_FILE="{args.mail_file}"')
EOF
    }

    TMP_OUTPUT=$(mktemp)
    parse_args "$@" > "$TMP_OUTPUT" 2>&1
    PYTHON_EXIT_CODE=$?

    # __HELP__ が含まれていたら eval しない
    if grep -q '__HELP__' "$TMP_OUTPUT"; then
        grep -v '__HELP__' "$TMP_OUTPUT"
        rm -f "$TMP_OUTPUT"
        exit 0
    fi

    # 成功時のみ eval 実行
    if [ "$PYTHON_EXIT_CODE" -eq 0 ]; then
        eval "$(cat "$TMP_OUTPUT")"
    else
        cat "$TMP_OUTPUT"
        rm -f "$TMP_OUTPUT"
        exit "$PYTHON_EXIT_CODE"
    fi

    rm -f "$TMP_OUTPUT"
}

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?