LoginSignup
0
0

More than 1 year has passed since last update.

pythonで書かれたコードの実行時に、別途用意したファイルを標準入力から入力する

Last updated at Posted at 2021-11-28

n版煎じですみません。
pythonで書かれたコードの実行時に、標準入力から別途用意したファイルを入力する方法メモ。

以下のようなコードがある場合

test.py
#!/bin/python3

line1 = input()
line2 = input()
print(line1)
print(line2)

何もせずに実行すると以下のようにCUIからの標準入力待ちになる。

$ python3 test.py
this_is_line1 ★入力する
this_is_line2 ★入力する
this_is_line1 ★出力される
this_is_line2 ★出力される

以下のようにすると別途用意したファイル(input.txt)を標準入力から入力できる。

$ python3 test.py < input.txt
this_is_line1
this_is_line2
input.txt
this_is_line1
this_is_line2

追記

(コメントでアドバイス頂いたように)
catの出力をパイプで渡した方が覚えやすい気がしています。

$ cat input.txt | python3 test.py
this_is_line1
this_is_line2
input.txt
this_is_line1
this_is_line2

参考

Pythonでcatみたいに標準入力またはファイル名指定でテキストを読み込む方法

0
0
2

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