【问题标题】:Save output of os.system to text file将 os.system 的输出保存到文本文件
【发布时间】:2018-01-25 11:17:57
【问题描述】:

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

我编写了一个小脚本来打开 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()

【问题讨论】:

  • @GeekSambhu 在写入模式下打开一个文件,如果它不存在则创建它(如果它存在则截断它),所以在附加模式下打开不会有太大变化(我的意思是 wrt/ 文件创建)。
  • os.system 直接写入其 shell 的 stdout,它的目的不是让您捕获该输出(尽管您可以通过 shell 重定向捕获它)。通常,您应该使用subprocess 函数之一,而不是非常原始的os.system
  • 如果您正在编写新代码,那么您现在绝对应该以 Python 3 为目标。

标签: python


【解决方案1】:

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

要捕获命令的输出,您必须使用subprocess 模块的一些功能,这里最明显的是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)

【讨论】:

  • @elarinya17 添加了一个问答示例(显然未经测试,因为我没有在此处安装 adb)。
  • 我遇到了一些错误,我认为是因为它不再识别 adb 命令了。
  • 好的,我修复了错误(只需要在 'devices' 和 '-l' 之间加一个逗号,但现在它根本没有运行 adb 命令,也没有创建文本文件
  • 是的,我也看到了错误(并在我的答案中修复了它)。 wrt/“它只是没有运行...”:如果您有错误,请发布错误消息、完整的回溯以及产生错误的 exact 代码(编辑您的问题,不要将此发布在评论中)。否则,在您的代码中添加一些跟踪(即print "calling command" 在子进程调用之前和print "out : '{}'".format(out) 在子进程调用之后。基本调试的东西真的。
  • @ModusTollens 你确实是对的,我的错。 elarinya17 如果你读到这个......
【解决方案2】:

尝试以下方法:

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) 

【讨论】:

  • 试过这个,它删除了 adb 命令的输出,仍然没有创建文本文件:(
  • 尝试打印 s 并查看里面有什么,不幸的是我无法安装 adb 来运行它,因为我在当前机器上没有 root 访问权限
  • 当我这样做时,它会准确地输出我需要的内容(已写入的所有内容),但我实际上仍然找不到文本文件?
  • 嗯很奇怪,尝试创建一个新文件夹,将脚本放入其中并从那里运行它,它会创建logfile.txt吗?
  • 是的,我是个白痴……我在原始 .py 文件所在的文件夹中寻找它,它在 platform-tools 文件夹中,现在我停下来很明显思考。 -_- 谢谢你的帮助!!
【解决方案3】:

感谢大家的帮助。答案是:

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)

【讨论】:

  • 这现在与接受的答案相同。也许只是删除它,因为它没有任何贡献。
  • 我只是把它留在这里,因为我之前没有发布它被告知,然后因为发布到错误的地方而被告知。
【解决方案4】:

在 Python 3.5+ 中,您可以(并且可能应该)使用 subprocess.run(),它可以方便地用更通用的 API 替换旧的 subprocess.check_output()

import subprocess

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

请注意,也可以通过旧的 check_output() API 将子进程的 stdout 直接连接到打开的文件句柄。

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多