サイトアイコン Python Snippets

標準入力から読み込む stdin , input

標準入力stdin

sysモジュールのstdinから標準入力のファイルオブジェクトが取得できる

# 標準入力から読み取って出力
import sys
for line in sys.stdin:
   print("--> " + line)

ファイルオブジェクトなのでreadやreadlinesなどの関数も使用可能。

コンソールから入力を受付, input (raw_input: python2)

CLIでのプロンプト入力待ちみたいなのはもっと便利な関数inputがあります。inputはpython3での関数でpython2のときはraw_inputでした。
ビルドイン関数なのでimportは不要。

>>> a = input("input your name: ")
input your name: taro
>>> a
'taro'
関連記事:

モバイルバージョンを終了