1 """A multithreaded version of os.popen2(). Note that the argument list
2 isn't quite the same."""
3
4
5 import os
6
7
8
9
11 __doc__ = """Pseudo-file descriptor. Just like a FD, except
12 that it waits for the process at the end of the pipe
13 to terminate when you close it.
14 """
15
30
31
34
35
38
39
42
43
46
47
48
51
52
55
56
57
58
61
62
64 if not self.closed:
65 self.fd.close()
66 self.closed = True
67 pid, t2 = os.waitpid(self.cpid, 0)
68 if t2 == 0:
69 self.waitval = None
70 else:
71 self.waitval = t2
72 return self.waitval
73
74
77
78
80 """Forks off a process, and returns the processes
81 input and output file descriptors. The latter is really
82 a pfd (defined above).
83
84 Path and args are passed directly into os.execvp().
85 """
86
87 rci, wci = os.pipe()
88 rco, wco = os.pipe()
89
90 cpid = os.fork()
91 if cpid == 0:
92
93 os.close(rco)
94 os.close(wci)
95 os.dup2(rci, 0)
96 os.dup2(wco, 1)
97 os.execvp(path, args)
98 os._exit(127)
99
100 os.close(rci)
101 os.close(wco)
102 return (os.fdopen(wci, "w"), pfd(rco, cpid))
103
104
106 si, so = popen2("sed", ["sed", "-e", "s/or/er/"])
107 si.write("hello, world!\nsecond line\n")
108 si.close()
109 assert so.readline() == "hello, werld!\n"
110 a = so.readlines()
111 assert len(a) == 1
112 assert a[0] == "second line\n"
113 tmp = so.close()
114 assert tmp is None
115
116 if __name__ == '__main__':
117 test()
118 test()
119