如何使用子进程写入文件

时间:2015-10-30 01:10:38

标签: android python python-2.7 subprocess logcat

我正在尝试获取adb logcat并保存到文件中。我试过POPEN并按以下方式打电话

    f = open("/Users/log.txt")
    subprocess.call(["adb logcat"], stdout=f)
    f_read = f.read()
    print f_read

但我收到错误

  File "testPython.py", line 198, in getadbLogs
    subprocess.call(["adb logcat"], stdout=f)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 522, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 710, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1335, in _execute_child
    raise child_exception
**OSError: [Errno 2] No such file or directory**

我不确定我做错了什么。是否可以使用子进程获取adb logcat日志?我检查了文件路径是对的。

1 个答案:

答案 0 :(得分:1)

因为您在阅读模式(f)中打开了r。如果您不选择模式,则默认模式为r模式。

要写入文件,您应该使用w模式,如下所示:

f = open("/Users/log.txt", 'w')
subprocess.call(["adb logcat"], stdout=f)
f.close()

f = open("/Users/log.txt")
f_read = f.read()
print f_read
f.close()

使用with自动关闭文件会更简单:

with open("/Users/log.txt", 'w') as f:
    subprocess.call(["adb logcat"], stdout=f)

with open("/Users/log.txt") as f:
    f_read = f.read()

print f_read