<Python> lsコマンド
ls
を実行して、ディレクトリdirectory
のファイルfile
をゲットする。
subprocess
を使う。
その1 .check_out()
In [1]: import subprocess In [2]: subprocess.check_output('ls', shell=True) Out[2]: b'aaa.html\nbbb2.html\nccc.csv\n'
ということで、なんだか、bytes
で結果が返ってくる。
ので、デコードする。
In [3]: o = subprocess.check_output('ls', shell=True) In [4]: o.decode('utf-8') Out[4]: 'aaa.html\nbbb2.html\nccc.csv\n' In [5]: print(o.decode('utf-8')) aaa.html bbb2.html ccc.csv
その2 .getoutput()
まずは、実行。
In [6]: subprocess.getoutput('ls', shell=True) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-0b9fae090776> in <module>() ----> 1 subprocess.getoutput('ls', shell=True) TypeError: getoutput() got an unexpected keyword argument 'shell'
エラー、、shell
が使えないらしいので、削る。
In [7]: subprocess.getoutput('ls') Out[7]: 'aaa.html\nbbb2.html\nccc.csv' In [8]: print(subprocess.getoutput('ls')) aaa.html bbb2.html ccc.csv
こっちは、文字列str
で返ってくる。
リストにするには、split()
をする。
In [9]: subprocess.getoutput('ls').split() Out[9]: ['aaa.html', 'bbb2.html', 'ccc.csv']
マニュアル。
17.5. subprocess — サブプロセス管理 — Python 3.5.1 ドキュメント
スタックオーバーフロー。