subprocess.Popen and ordering writes to stdout and stderr

Discussion in 'Python' started by Chris Withers, Dec 17, 2009.

  1. Hi All,

    I have this simple function:

    def execute(command):
    process = Popen(command.split(),stderr=STDOUT,stdout=PIPE)
    return process.communicate()[0]

    ...but my unit test for it fails:

    from testfixtures import tempdir,compare
    from unittest import TestCase

    class TestExecute(TestCase):

    @tempdir()
    def test_out_and_err(self,d):
    path = d.write('test.py','\n'.join((
    "import sys",
    "sys.stdout.write('stdout\\n')",
    "sys.stderr.write('stderr\\n')",
    "sys.stdout.write('stdout2\\n')",
    )),path=True)
    compare('stdout\nstderr\nstdout2\n',
    execute(sys.executable+' '+path))

    ....because:

    AssertionError:
    @@ -1,4 +1,4 @@
    -stdout
    -stderr
    -stdout2
    +stdout
    +stdout2
    +stderr

    ....the order of the writes isn't preserved.
    How can I get this to be the case?

    Chris

    --
    Simplistix - Content Management, Batch Processing & Python Consulting
    - http://www.simplistix.co.uk
    Chris Withers, Dec 17, 2009
    #1
    1. Advertising

  2. Chris Withers

    Lie Ryan Guest

    On 12/18/2009 8:15 AM, Chris Withers wrote:
    >
    > ....the order of the writes isn't preserved.
    > How can I get this to be the case?
    >


    You'll need to flush the std{out|err} or set them unbuffered; or you can
    just forget about relying on std{out|err} being ordered per write-order.
    Lie Ryan, Dec 18, 2009
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Roman Neuhauser
    Replies:
    0
    Views:
    644
    Roman Neuhauser
    Apr 4, 2005
  2. Fuzzyman
    Replies:
    3
    Views:
    618
    Gabriel Genellina
    Jan 7, 2007
  3. Leon Derczynski
    Replies:
    2
    Views:
    403
    Nobody
    Aug 24, 2010
  4. goldtech
    Replies:
    2
    Views:
    1,510
    goldtech
    Apr 19, 2011
  5. Une Bévue
    Replies:
    1
    Views:
    136
    Justin Collins
    Feb 27, 2008
Loading...

Share This Page