def cmd(cmd, fd={}, e={}, cd=None): """ Perform a fork-exec-wait of a Cmd and return the its stdout as a byte string. """ f = Cmd(cmd, fd=fd, e=e, cd=cd).capture(1).stdout try: s = f.read() finally: f.close() return s
def test_capture_timeout(self): ## make sure that capture doesn't return instantly cmd = Cmd("/bin/sh -c 'sleep 1 && echo foo'") self.assertSh( cmd.capture(1).stdout.read(), 'foo') ## make sure that timeout is honored, this process should take ## too long and be terminated cmd = Cmd("/bin/sh -c 'sleep 5 && echo foo'") self.assertSh( cmd.capture(1, timeout=1).stdout.read(), '')
def test_capture(self): self.assertSh( Cmd("/bin/sh -c 'echo foo'").capture(1).stdout.read(), 'foo') self.assertSh( Cmd("/bin/sh -c 'echo bar >&2'").capture(2).stderr.read(), 'bar') c_obj = Cmd("/bin/sh -c 'echo foo; echo bar >&2'") cout, cerr, status = c_obj.capture(1, 2) self.assertSh(cout.read(), 'foo') self.assertSh(cerr.read(), 'bar')
def test_wait_callback(self): orig_val = [0] def val_mod(): orig_val[0] = 8 c = Cmd("sleep 1") c.spawn() self.assertEquals(orig_val, [0]) c.wait(val_mod) self.assertEquals(orig_val, [8]) orig_val = [0] p = Cmd("echo foo").pipe_to(Cmd("wc -c")) p.spawn() self.assertEquals(orig_val, [0]) p.wait(val_mod) self.assertEquals(orig_val, [8]) if __name__ == '__main__': unittest.main()
def _test_popen_fd_semantics(self): tf = tempfile.TemporaryFile() ab = Cmd('yes', {STDOUT: tf}) ab._popen() self.assertTrue(tf is ab.fd_objs[STDOUT])
def test_spawn_once(self): ab = Cmd('yes', {STDOUT: '/dev/null', STDERR: '/dev/null'}) ab.spawn() self.assertRaises(Exception, lambda: ab.spawn())