2
1

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】sysモジュールの使い方

Posted at

Pythonで学ぶ sys モジュールの使い方入門

Pythonのsysモジュールを使うと、コマンドライン引数やシステムの状態にアクセスできます。この記事では、sys.argvを使ってコマンドライン引数を処理する実用例を紹介します。


✅ 基本:sys.argv とは?

sys.argv は、Pythonスクリプトに渡された引数のリストです。

import sys
print(sys.argv)

上記スクリプトを以下のように実行すると:

python sample.py -m 6

出力は以下のようになります:

['sample.py', '-m', '6']
  • sys.argv[0] → スクリプトのファイル名
  • sys.argv[1] 以降 → 実際に渡された引数

✅ 実用例:引数で月を指定できるカレンダー

以下のように、-m オプションを使って特定の月のカレンダーを出力するスクリプトを作成できます。

import datetime
import sys
from datetime import date, timedelta

args = sys.argv[1:] # 初項にファイル名が入るが不要なため[1:]とする

today = datetime.date.today()
month = today.month
year = today.year

# オプション処理
if len(args) == 0:
    pass  # 現在の年月を使う
elif len(args) == 2 and args[0] == "-m":
    if args[1].isdigit():
        month = int(args[1])
        if not (1 <= month <= 12):
            print(f"{args[1]} is neither a month number (1..12) nor a name")
            sys.exit()
    else:
        print(f"{args[1]} is neither a month number (1..12) nor a name")
        sys.exit()
else: # 適当な引数に対して
    print(f"{' '.join(args)} is neither a month number (1..12) nor a name")
    sys.exit()

# カレンダー出力
print(f"{year}{month}")
print("Mo Tu We Th Fr Sa Su")

first_day = date(year, month, 1)
start_weekday = first_day.weekday()  # 0=Monday, 6=Sunday

# 月末を求める
if month == 12:
    last_day = date(year + 1, 1, 1) - timedelta(days=1)
else:
    last_day = date(year, month + 1, 1) - timedelta(days=1)

# カレンダー本体出力
day = 1
print("   " * start_weekday, end="") # スタート位置までのスペース
while day <= last_day.day:
    print(f"{day:2}", end=" ")
    start_weekday += 1
    if start_weekday == 7:
        start_weekday = 0
        print()
    day += 1

使用例

python calendar.py           # 今月のカレンダー
python calendar.py -m 6      # 6月のカレンダー
python calendar.py -m hoge   # エラー表示

引数処理のポイント

args = sys.argv[1:]  # 最初の要素(スクリプト名)を除外

if len(args) == 0:
    # 引数なし → 現在の年月を使用
elif len(args) == 2 and args[0] == "-m":
    # 正しい形式 → -m のあとに数字(1〜12)が来ているかをチェック
    ...
else:
    # 異常系 → 不正なオプションや引数の数
    ...

✅ よくあるミス

  • sys.argv[-1] で最後の引数だけ見てしまうと、オプションが正しく処理されません。
  • 引数の数や順序をきちんとチェックしないとバグの原因になります。

📝 まとめ

  • sys.argv を使えば、Pythonスクリプトにインタラクティブに引数を与えられる
  • 実用的なスクリプトを通して、条件分岐とエラーハンドリングの重要性も理解できる

ぜひ自分でもカスタマイズして、コマンドラインツールの基礎を身につけましょう!

2
1
0

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?