如何使用子进程写入文件
How to use subprocess to write to file
我正在尝试获取 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 日志?我检查了文件路径是否正确。
因为您以阅读模式打开了 f
(r
)。如果你不select模式,默认模式是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
我正在尝试获取 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 日志?我检查了文件路径是否正确。
因为您以阅读模式打开了 f
(r
)。如果你不select模式,默认模式是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