Save output of os.system to text file

后端 未结 4 428
悲&欢浪女
悲&欢浪女 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:05

    Try the following:

    import os 
    import subprocess 
    import time 
    
    print ('Current Directory: {}'.format(os.getcwd()) ) 
    print ('Opening Android SDK...') 
    os.chdir('C:\\android-sdk\\platform-tools') 
    print ('Current Directory: {}'.format(os.getcwd()) )
    t = str(time.ctime()) 
    try:
        process_output = subprocess.check_output(["adb", "devices", "-l"])
    except: #Add here the type of exception you want to raise and logic
        print("Please check your ADB installation and syntax.")
    s = ('{} Checking for connected devices: {}'.format(t,process_output) ) 
    with open('logfile.txt', 'w') as f:
        f.write(s) 
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-04 01:10

    With Python 3.5+ you can (and probably should) use subprocess.run() which conveniently replaces the legacy subprocess.check_output() with a more versatile API.

    import subprocess
    
    with open('logfile.txt', 'w') as f:
        subprocess.run(['adb', 'devices', '-l'], stdout=f,
            universal_newlines=True)  # this obscurely makes everything Unicode
    

    Directly connecting the stdout of the subprocess to an open file handle is possible via the old check_output() API too, mind you.

    0 讨论(0)
  • 2020-12-04 01:26

    Thanks everyone for your help. The answer was:

    import os
    import time
    import subprocess
    
    print 'Current Directory:', os.getcwd()
    print 'Opening Android SDK...'
    os.chdir('C:\\android-sdk\\platform-tools')
    print 'Current Directory:', os.getcwd()
    print 'Checking for connected devices:'
    t = time.ctime()
    # save log of time and connected devices
    with open('logfile.txt', 'w') as f:
        s = ('{}\n{}'.format(t, subprocess.check_output(["adb", "devices", "-l"])))
        f.write(s)
    print(s)
    
    0 讨论(0)
提交回复
热议问题