os.popen在Python 2.6真的是不推荐使用吗?
在线的文档提到,os.popen这个函数现在已经不推荐使用了。其他不推荐的函数通常会发出一个警告,叫做DeprecationWarning。比如:
>>> import os
>>> [c.close() for c in os.popen2('ps h -eo pid:1,command')]
__main__:1: DeprecationWarning: os.popen2 is deprecated. Use the subprocess module.
[None, None]
但是,os.popen这个函数却没有任何提示,默默地完成了任务:
>>>len(list(os.popen('ps h -eo pid:1,command')))
202
没有发出任何警告。在可能的三种情况中:
- 文档和标准库对什么是不推荐使用的有不同的看法,这种情况是可以预期的;
- 文档有错误,os.popen其实并没有被不推荐使用;
- 标准库有错误,os.popen应该发出警告;
那么,哪一种情况是正确的呢?
为了提供一些背景信息,这里是我使用的Python版本:
>>> import sys
>>> print sys.version
2.6.2 (r262:71600, May 12 2009, 10:57:01)
[GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)]
传给os.popen的参数来自我在Stack Overflow上的一个回答。
补充说明:感谢cobbal在下面的提醒,实际上os.popen在Python 3.1中并没有被不推荐使用。
4 个回答
3
与此同时,我在Python的问题追踪网站上开了一个问题单。我会把这个问题保持开放状态,直到那个问题单解决为止。
4
我想到的一件事是,Python 3里有os.popen这个功能,但没有os.popen2。所以说,os.popen2这个功能“被淘汰得更早”,也就是说它可能会更快地从这个语言中被移除。
5
这里是这个PEP的链接。
Deprecated modules and functions in the standard library: - buildtools - cfmfile - commands.getstatus() - macostools.touched() - md5 - MimeWriter - mimify - popen2, os.popen[234]() - posixfile - sets - sha