将 os.system 的输出保存到文本文件

2023-12-21

我不太擅长所有技术术语,所以我会尽力解释我的问题。

我编写了一个小脚本来打开 android SDK 并检查连接的设备(使用 windows 10 和 python 2.7.14)。我得到的代码如下:

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')

一切正常,但我想将最后 3 行保存到文本文件中。我试过了f = open('logfile.txt', 'w')然后使用将其全部转换为字符串s = str(t, 'Checking for connected devices:', os.system('adb devices -l'))并将其写入文件并关闭它,但它不起作用。它甚至没有创建文件,更不用说向其中写入任何内容了。

我可能错过了一些关键的东西,但我是这方面的新手,所以请友善!

任何帮助将非常感激。

非常感谢

编辑:包含写入内容的整个代码:

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()

os.system在子 shell 中执行命令并返回命令的退出代码。它不提供任何捕获命令输出的方法(“输出”=> 命令打印到其 stdout/stderr 流的内容)。

要捕获命令的输出,您必须使用一些subprocess模块的功能,最明显的是subprocess.check_output https://docs.python.org/3/library/subprocess.html#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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 os.system 的输出保存到文本文件 的相关文章

随机推荐