Save output of os.system to text file

后端 未结 4 427
悲&欢浪女
悲&欢浪女 2020-12-04 00:42

I\'m not great on all the technical terms so I\'ll do my best to explain my problem.

I\'ve written a small script to open android SDK and check for attached devices

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-04 01:07

    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)
    

提交回复
热议问题