LoginSignup
7
19

More than 1 year has passed since last update.

python3で外部のシェルスクリプト(ls)とかの返り値(と終了コード)を取得。

Last updated at Posted at 2017-01-15

1.やりたいこと

Python3からlsとかpwdを叩いて返り値をGetしたい。
いつも忘れるのでメモ
他の記事は少々古いので新たな気分で
lsなら glob.glob 使えやとか聞こえてきますが、今回はスルーの方向で。

2.書き方(command -> subprocess)

command.getoutput(cmd) 1

subprocess.getoutput(cmd)2 になっただけ

shellの返り値Get!

# 3系ではcommandは廃止されたので代わりにsubprocess使う
from subprocess import getoutput  

ls = getoutput('ls')
print(ls)
 # lsの返り値(str)

pwd = getoutput('pwd')
print(pwd)
 # 現在ディレクトリの絶対パス(str)


top = getoutput('top') # 永遠に帰ってこない

2021/10/17 追記:
終了コードも欲しい場合は getstatusoutput() が使用できる3

from subprocess import getstatusoutput

# 単純な ls で正常終了する
ls = getstatusoutput('ls')
print(ls)
# (0, '[ls の結果]')

# hoge というディレクトリが無いのでエラーになり、終了コードは `1` になる。
cd = getstatusoutput('cd hoge')
print(cd)  # hoge というディレクトリが無いのでエラーになり、終了コードは `1` になる。
# (1, '/bin/sh: line 0: cd: hoge: No such file or directory')

以上

7
19
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
7
19