Save output of os.system to text file

os.system executes the command in a subshell and returns the command’s exit code. It does not provide any mean to capture the outputs of the command (“outputs” => what the command prints to it’s stdout/stderr streams).

To capture the command’s outputs you’ll have to use some of the subprocess module’s feature, the most obvious here being subprocess.check_output

# ...
import subprocess
# ...
# NB : you may want to catch subprocess.CalledProcessError here
out = subprocess.check_output(['adb',  'devices', '-l'])
msg = "{t}\nChecking for connected devices:\n{out}".format(t=t, out=out)
with open('logfile.txt', 'w') as f:
    f.write(msg)

Leave a Comment