subprocessコマンド結果をリスト保存

投稿者: | 9月 19, 2022

リストとfor文で実行

import subprocess
from pprint import pprint

output = subprocess.getoutput('ls -l')

result0 = []
lines0 = output.splitlines()
for line0 in lines0:
    line1 = line0.split()
    result0.append(line1)
pprint(result0, width=88)

リスト内包で実行

import subprocess
from pprint import pprint

output = subprocess.getoutput('ls -l')
result1 = [line.split() for line in output.splitlines()]
pprint(result1, width=88)

結果

[['total', '8'],
 ['drwxr-xr-x', '5', 'mash', 'staff', '160', '9', '17', '09:23', 'Flask_Apps'],
 ['-rw-r--r--', '1', 'mash', 'staff', '114', '9', '16', '12:39', 'README.md'],
 ['drwxr-xr-x', '7', 'mas', 'staff', '224', '9', '19', '01:54', 'flaskbook'],
 ['drwxr-xr-x', '5', 'mash', 'staff', '160', '9', '9', '13:34', 'powershell'],
 ['drwxr-xr-x', '8', 'mash', 'staff', '256', '9', '19', '00:46', 'python']]