writing consecutive data to subprocess command 'more'

Piet van Oostrum piet at cs.uu.nl
Sat May 2 16:37:24 EDT 2009


>>>>> SanPy <jhmsmits at gmail.com> (S) wrote:

>S> I have this method that prints a given text via a subprocess command
>S> 'more' . It is like this:

>S> def print_by_page(text):
>S>     if hasattr(sys.stdout, 'isatty') and sys.stdout.isatty():
>S>         viewer = 'more -EMR'
>S>         proc = subprocess.Popen([viewer], shell=True,
>S> stdin=subprocess.PIPE,
>S>             stderr=subprocess.PIPE)
>S>         try:
>S>             stdout, stderr = proc.communicate(text)
>S>         except OSError:
>S>             pass
>S>         else:
>S>             if stderr: # probably no 'more' available on this system
>S>                 sys.stdout.write(text)
>S>             return
>S>     sys.stdout.write(text)

>S> It works fine, but what I really want to do is first print a header
>S> through the 'more' command, then fetch some data from the web, and
>S> show it through the same 'more' command/process. And even more data,
>S> another header, other data from the web, all through the same 'more'
>S> command/process.
>S> Can somebody help me out on this?

You have to split this. Do the startup (creating the subprocess) once,
and then for each piece of text that you want to pass through 'more' do
stdout, stderr = proc.communicate(text)

By the way, in this last line, stdout should come out empty because the
output of more doesn't come back to the parent process, but goes to the
original stdout of the calling script.

Also I would use the following:
    viewer = ['more', '-EMR']
    proc = subprocess.Popen(viewer, stdin=subprocess.PIPE, 
                                    stderr=subprocess.PIPE)
No reason to use a shell.

And if there is no 'more' available you get an exception on the Popen
already. You don't have to wait until the communicate call.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list