このエントリーをはてなブックマークに追加


パイプで渡されたstdinの有無を確認する方法

ターミナルからパイプで渡された文字列群があるかどうかを確認するPythonサンプルコードを以下に記します。


スポンサーリンク

関連記事

パイプ渡しのstdinの有無確認サンプル

以下、Python2, Python3のサンプルコードおよび実行例を記します。

Python2向け

使用したPythonは以下の通りです。

$ python --version
Python 2.7.9
#!/usr/bin/env python

import sys
import select


def isPipe():
    if select.select([sys.stdin,],[],[],0.0)[0]:
        return True
    return False

if isPipe():
  print sys.stdin.readlines()
else:
  print "nothing"

以下、実行したときの出力です。
パイプ渡しのstdinの有無が確認できていることがわかります。

sakura@debian:~$ chmod +x ispipe2.py
sakura@debian:~$ ./ispipe2.py
nothing
sakura@debian:~$ echo SAKURA | ./ispipe2.py
['SAKURA\n']

Python3向け

使用したPython3は以下の通りです。

$ python3 --version
Python 3.4.2
#!/usr/bin/env python3

import sys
import select


def isPipe():
    if select.select([sys.stdin,],[],[],0.0)[0]:
        return True
    return False

if isPipe():
  print(sys.stdin.readlines())
else:
  print("nothing")

以下、実行したときの出力です。
パイプ渡しのstdinの有無が確認できていることがわかります。

sakura@debian:~$ chmod +x ispipe3.py
sakura@debian:~$ ./ispipe3.py
nothing
sakura@debian:~$ echo SAKURA | ./ispipe3.py
['SAKURA\n']

以上、Pythonでパイプ渡しのstdinの有無を確認する方法でした。


スポンサーリンク


添付ファイル: fileispipe2.py 445件 [詳細] fileispipe3.py 431件 [詳細]

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2016-12-07 (水) 21:26:01