bufsize in subprocess

Y

yves

Is this the expected behaviour?
When I run this script, it reads only once, but I expected once per line with
bufsize=1.

What I am trying to do is display the output of a slow process in a tkinter
window as it runs. Right now, the process runs to completion, then display the
result.

import subprocess

com = ['/bin/ls', '-l', '/usr/bin']
with subprocess.Popen(com, bufsize=1, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT) as proc:
print('out: ' + str(proc.stdout.read(), 'utf8'))


Thanks.
 
C

Chris Rebert

Is this the expected behavior?

Yes. `.read()` [with no argument] on a file-like object reads until
EOF. See http://docs.python.org/library/stdtypes.html#file.read
When I run this script, it reads only once, but I expected once per line
with bufsize=1.

You want proc.stdout.readline().
http://docs.python.org/library/stdtypes.html#file.readline
What I am trying to do is display the output of a slow process in a tkinter
window as it runs. Right now, the process runs to completion, then display
the result.

   import subprocess

   com = ['/bin/ls', '-l', '/usr/bin']
   with subprocess.Popen(com, bufsize=1, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT) as proc:
       print('out: ' + str(proc.stdout.read(), 'utf8'))

Cheers,
Chris
 
Y

yves

Is this the expected behavior?

Yes. `.read()` [with no argument] on a file-like object reads until
EOF. See http://docs.python.org/library/stdtypes.html#file.read

Right, got it now.
You want proc.stdout.readline().

Yes, or a for loop, this works for me now:


import subprocess

com = ['/bin/ls', '-l', '/usr/bin']
with subprocess.Popen(com, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT) as proc:
for line in proc:
print('out: ' + str(line, 'utf8'))
 
Y

yves

import subprocess

com = ['/bin/ls', '-l', '/usr/bin']
with subprocess.Popen(com, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
as proc:
for line in proc.stdout:
print('out: ' + str(line, 'utf8'))
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top