Python os.popen close:IOError
来自个人维基
前提:手机未连上adb
版本:
F:\W\MP\trunk\python> python --version Python 2.7.3
执行如下脚本:
import os import traceback fout = os.popen("adb shell ls /system/bin/abcd") fout.close() print 'hello'
==>
F:\W\MP\trunk\python> python pytest.py Traceback (most recent call last): File "pytest.py", line 5, in <module> fout.close() IOError: [Errno 0] Error
对IOError进行catch后,虽也会抛出异常,但被catch后不会影响脚本的运行:
import os import traceback try: fout = os.popen("adb shell ls /system/bin/abcd") fout.close() except IOError: #traceback.print_exc() pass print 'hello'
==>
F:\W\MP\trunk\python> python pytest.py hello
原因:python的一个bug,即当os.popen执行任务失败,返回负数时,在close时会抛出上述异常:
http://bugs.python.org/issue602245
另外,现在也不建议用os.popen,推荐使用 subprocess:
http://www.gossamer-threads.com/lists/python/bugs/615568?do=post_view_threaded#615568