ターミナルからパイプで渡された文字列群があるかどうかを確認するPythonサンプルコードを以下に記します。
以下、Python2, Python3のサンプルコードおよび実行例を記します。
使用した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 --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の有無を確認する方法でした。