1.僵尸进程的解决方法
os.popen 打开后需要用 close 方法回收资源 避免僵尸进程
下面是产生僵尸进程的例子。
调用os模块,使用popen方法执行一个命令,可以看到在进程中产生了一个僵尸进程。如果关掉这个进程,只需要在后面加入close()函数即可。
2.
返回值的注意事项
- 检查 shell 命令是否执行成功
- 回收子进程的资源
对于第一点,如果我们只是调用一些简单的 shell 命令,比如 ls/date/git
之类的话,倒是一般不需要担心执行可能会失败;
对于第二点,回收子进程的资源 调用 close()
即可。因为 os.popen
返回的是一个 file object
,抽象了一层 file-like 的接口,这也是我们可以对其调用 read()
,甚至 write()
的原因;同理,类似 file 的操作,我们可以在 os.popen()
之后调用 close()
:
sh_pipe = os.popen('date')
now = sh_pipe.read()
# do something with @now ...
sh_pipe.close()
这里调用的 close()
,内部封装了 wait()
调用,完成对子进程资源回收
3.使用实例
sh_pipe = os.popen('date')
exit_status = sh_pipe.close()
if exit_status == 0:
now = sh_pipe.read()
# do something with @now
else:
# do some exception work here..
或者,我们可以借助 with
语法糖,写出更简洁的代码:
with os.popen('date') as sh_pipe:
now = sh_pipe.read()
# do something with @now
因为 os.popen()
返回的 file-like object 封装了 __enter__
和 __exit__
方法,我们借助 context 机制实现对 close()
的自动调用。
4.使用建议
这个函数在 Python 2.6 之后已经被标记为被废弃
subprocess 是 Python 官方建议的 os.popen() 的替代方式,甚至提供了迁移示例:
pipe = os.popen("cmd", 'r', bufsize)
==>
pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout