Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

python - Save output of os.system to text file

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 (using windows 10 and python 2.7.14). The code I've got is as follows:

import os
import datetime
import time

print 'Current Directory:', os.getcwd()
print 'Opening Android SDK...'
os.chdir('C:\android-sdk\platform-tools')
print 'Current Directory:', os.getcwd()
t = time.ctime()
print t
print 'Checking for connected devices:'
os.system('adb devices -l')

That all works fine, but I want to get the last 3 lines to save to a text file. I've tried f = open('logfile.txt', 'w') then converting it all to a string using s = str(t, 'Checking for connected devices:', os.system('adb devices -l')) and writing it to the file and closing it, but it's not working. It's not even creating the file, let alone writing anything to it.

I'm probably missing something key but I'm a newbie at this so please be nice!

Any help would be much appreciated.

Many thanks

Edit: whole code with the write stuff included:

import os
import datetime
import time

print 'Current Directory:', os.getcwd()
print 'Opening Android SDK...'
os.chdir('C:\android-sdk\platform-tools')
print 'Current Directory:', os.getcwd()
t = time.ctime()
f = open('logfile.txt', 'w')
s = str(t, 'Checking for connected devices:', os.system('adb devices -l'))
f.write(s)
f.close()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}
Checking for connected devices:
{out}".format(t=t, out=out)
with open('logfile.txt', 'w') as f:
    f.write(msg)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...