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?

More than 3 years have passed since last update.

[記録]コマンドライン引数について

Posted at

はじめに

最近Djangoを触り始めたのだが、よく「python manage.py runserver」 (「python モジュール名 コマンド」)のようなコマンドを打つことがあり、モジュール名の後にコマンドを打つとなぜ特定の動きをするのか疑問に思った。

参考はネットで見つけた以下の記事 >https://qiita.com/Tadahiro_Yamamura/items/cecbc27182b76257d18f >https://techacademy.jp/magazine/20629

コマンドライン引数

「python モジュール名 コマンド」のコマンドの部分はコマンドライン引数というらしい。イメージとしては、関数における引数とほぼ同じだろう。 このコマンドライン引数はsysモジュールのargvという配列に格納されるらしい。

sys.argvについて

上記でも行ったがsys.argvはコマンドライン引数のリストである。ただし、先頭(srgv[0])はスクリプトの名前である。つまり、実行されるモジュール名が格納される。

使い方

以下は入力したコマンドをすべて表示するプログラム。

name.py
import sys

for comand_name in sys.arg:
 print(comand_name)

コマンドは「python モジュール名 コマンド コマンド(以下略)」のようにスペースを空けて何個でも入力できる。

最後に

今回はコマンドライン引数について自分の復習のためにまとめてみました。プログラミング初学者なので言い回しや用語の使い方などに違和感や誤りがあるかもしれません。

Djangoで使うようなコマンドの仕組みとあってるか違っているかもわからないが、何となく裏側で何が起こっているのかが把握できただけでも見通しが晴れて学びやすくなった。

0
0
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
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?