首页 > 其他 > 详细

os.pipe learning tips

时间:2014-03-18 17:27:45      阅读:436      评论:0      收藏:0      [点我收藏+]


os.pipe() 典型用法:


#!/usr/bin/python

import os, sys

print "The child will write text to a pipe and "
print "the parent will read the text written by child..."

# file descriptors r, w for reading and writing
r, w = os.pipe() 

processid = os.fork()
if processid:
    # This is the parent process 
    # Closes file descriptor w
    os.close(w)
    r = os.fdopen(r)
    print "Parent reading"
    str = r.read()
    print "text =", str
    os.waitpid(processid, 0) # wait for child process terminate
    sys.exit(0)
else:
    # This is the child process
    os.close(r)
    w = os.fdopen(w, ‘w‘)
    print "Child writing"
    w.write("Text written by child...")
    w.close()
    print "Child closing"
    sys.exit(0)

os.pipe() 的代码实现:

Tracing into module of os (os.py), and find there nothing about function of pipe(), except the following code clips:

_names = sys.builtin_module_names # names of built-in modules, with Windows OS, there will be an item of ‘nt‘ within this tuple, while on Posix (Unix, linux), there will be an item of ‘posix‘ 

# Note:  more names are added to __all__ later.
__all__ = ["altsep", "curdir", "pardir", "sep", "extsep", "pathsep", "linesep",
           "defpath", "name", "path", "devnull",
           "SEEK_SET", "SEEK_CUR", "SEEK_END"]

def _get_exports_list(module): # this function will get all the attributes which not starts with "_"
    try:
        return list(module.__all__)
    except AttributeError:
        return [n for n in dir(module) if n[0] != ‘_‘]

if ‘posix‘ in _names:
    name = ‘posix‘
    linesep = ‘\n‘
    from posix import * # import all the attributes of posix, within which pipe() is implemented as well as other posix system calls
    try:
        from posix import _exit
    except ImportError:
        pass
    import posixpath as path # that‘s where os.path come from

    import posix
    __all__.extend(_get_exports_list(posix)) # add all the attributes of posix to var __all__
    del posix

We can find that, function of pipe() is implemented within this built-in module posix. Currently will just skip the source code of this.


os.pipe() 的其他用法:


Another scenario of using os.pipe() is subprocess. The following source code comes from subprocess.py



os.pipe learning tips,布布扣,bubuko.com

os.pipe learning tips

原文:http://blog.csdn.net/ispcfs/article/details/21468951

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!