1

I am trying to get adb logcat and save to a file. I tried POPEN and call as below

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

But I get error

  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**

I am not sure what I am doing wrong. Is it possible to get adb logcat logs using subprocess? I checked the file path is right.

user2661518
  • 2,677
  • 9
  • 42
  • 79

1 Answers1

1

Because you opened f in read mode(r). If you don't select the mode, the default mode is r mode.

To write to the file you should use w mode like this:

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

And use with to auto close the file would be more simple:

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
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
  • yes I just figured it as well. But since it's adb logcat it continuously keeps dumping to file. How should I stop/ kill it? – user2661518 Oct 30 '15 at 01:29
  • 1
    @user2661518 You could set the timeout, for example: `subprocess.call('python', timeout=2)` will only run python for 2 seconds. And then `subprocess` will raise `subprocess.TimeoutExpired` error and says: `Command 'python' timed out after 2 seconds`. – Remi Guan Oct 30 '15 at 01:34
  • since I'm using python2.7 subprocess.call does not have timeout argument – user2661518 Oct 30 '15 at 01:41
  • 1
    @user2661518: Well, take a look [here](http://stackoverflow.com/questions/1191374/subprocess-with-timeout) and [here](http://stackoverflow.com/questions/23287689/how-to-make-a-subprocess-call-timeout-using-python-2-7-6). – Remi Guan Oct 30 '15 at 01:45