8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonでシェルのコマンドを実行する

Last updated at Posted at 2014-10-05

シェルコマンドを利用したスクリプトを書くときってみなさんはどうしてるんですかね?
僕はPHPerなんで、phpで書きたくなるんですが今回はPythonで遊んでみました。

Pythonにはどうやらshってライブラリがあるらしくてそれを今回は利用してみました。

shtest.py
# -*- coding: utf-8 -*-
from sh import ls
from sh import sort
from sh import cat
from sh import cd


cd("./texts")
ls1 = ls.bake('-1')

# ls -1
print(ls1())
# 実行結果
# mike_oldfiled.txt
# miles_davis.txt
# pink_floyd.txt

# ls -1 | sort -rを実行
contents = map(lambda (i,f): "(%d)%s: %s"%(i+1,f.strip().rjust(20),cat(f.strip()).strip()),enumerate(sort(ls1(),'-r')))
for content in contents:
  print content

# [実行結果]
# (1)      pink_floyd.txt: Echoes(16:31)
# (2)     miles_davis.txt: So What(9:08)
# (3)   mike_oldfiled.txt: Amarok(1:00:03)

気軽にshel使えるところがいいですね。
bakeとかでオプション最初から設定出来るし。

基本的に書きやすいしいいんだけど、lamdbaが1行ってのはつらいお・・・

8
9
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
8
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?