LoginSignup
0
0

More than 3 years have passed since last update.

【Python】を使ってターミナル1で入力した情報をターミナル2で表示してみた【需要無し】

Last updated at Posted at 2021-04-24

開発環境

Python 3.9.2
Windows10 Home
Windows10標準コマンドプロンプト

開発経緯

なんとなく。
なんかできたら面白いから。

本編

システムとしては、
ターミナル1(以降 T1)で文字を入力→ファイルにその情報を保存→ターミナル2(以降 T2)でファイルの変更を認識→T2で出力
でやっていきます。

用意するファイルは
・input.py
・output.py
・file.txt
の三つ。
別に名前は何でもいいです。

コーディング

input

文字入力する方のファイルでは、
文字入力→ファイルに情報書き込み
をループさせていく感じでやっていきます。
簡単ですね。

input.py
while True:
    s = input()
    with open('file.txt', 'w', encoding='utf-8') as file:
        file.write(s)

たった4行。とても簡素。
これでT1で実行するファイルは完成です。

output

文字出力する方のファイルでは
ファイル内容を確認→前回の内容と比較→内容が違ったら内容を出力
をループします。
とても簡単。

output.py
with open('file.txt', 'r', encoding='utf-8') as file:
    before = file.read()
import time    
while True:
    with open('file.txt', 'r', encoding='utf-8') as file:
        cnt = file.read()
    if not cnt == before:
        before = cnt
        print(cnt)
    time.sleep(0.00001)

inputよりは行数が多いけどそれでも少ないですね。
time.sleepを途中に挟んでいる理由として、「ファイルの開閉を高速で行いすぎるとファイル内容が無になることがある」からですね。
sleep挟んだら解決したのでそうなんだろうっていう仮説ですけどね。
もしくは、ファイルの内容がなければ何もしないという処理を挟むのもいいかもしれませんね。
T2で実行するファイルもこれで完成です。

file.txtの内容は何も書かなくて大丈夫です。

実行

もう完成です。あとは実行するだけですね。
実際に実行してみると、

Animation.gif

はい、うまくいきましたね。
意外とファイルの読み書き速度が速かったです。
これの使い道を考えた人の勝ちっていうことにします。
コメント欄で遊んでください。

ノシ

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