def xsystem(cmd, inputdata=None): """ Run 'cmd' and return its output in a string. Optionally, 'inputdata' is written into command's stdin. """ try: pipe = Popen(cmd, stdout=PIPE, stdin=PIPE) except OSError: warning('Unable to run %s\n' %(' '.join(cmd))) return None if inputdata: try: pipein = pipe.stdin pipein.write(inputdata) except IOError: warning("IOError while writing to command %s\n" %(' '.join(cmd))) return None finally: pipein.close() try: pipeout = pipe.stdout result = pipeout.read() except IOError: warning("IOError while reading from command %s\n" %(' '.join(cmd))) return None finally: pipeout.close() pipe.wait() if pipe.returncode != 0: warning('%s did not exit cleanly\n' %(' '.join(cmd))) return None return result
def xrun(cmd, cb, ctx, inputdata=None): """ Run 'cmd' (a list of command line arguments). Call cb(data, ctx), when the command finishes with its output given to cb() at parameter 'data'. If 'inputdata' is given, feed it to the command from stdin. The result is relayed through the gobject mainloop. """ (rfd, wfd) = xpipe() if rfd < 0: return False pid = xfork() if pid == -1: warning('Could not fork a new process\n') return False if pid != 0: xclose(wfd) return xrunwatch(rfd, cb, ctx, pid) xclose(rfd) w = fdopen(wfd, 'w') try: pipe = Popen(cmd, stdout=PIPE, stdin=PIPE) except OSError: warning('Unable to run %s\n' %(' '.join(cmd))) w.write('-1\0') abort() w.write(str(pipe.pid) + '\0') w.flush() if inputdata: try: pipein = pipe.stdin pipein.write(inputdata) except IOError: warning("IOError while writing to command %s\n" %(' '.join(cmd))) abort() pipein.close() try: pipeout = pipe.stdout result = pipeout.read() except IOError: warning("IOError while reading from command %s\n" %(' '.join(cmd))) abort() pipeout.close() pipe.wait() if pipe.returncode != 0: warning('%s did not exit cleanly\n' %(' '.join(cmd))) abort() w.write(result) w.close() abort()