473,837 Members | 1,523 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Working around buffering issues when writing to pipes

Keywords: subprocess stdout stderr unbuffered pty tty pexpect flush setvbuf

I'm trying to find a solution to <URL:http://bugs.python.org/issue1241>. In
short: unless specifically told not to, normal C stdio will use full output
buffering when connected to a pipe. It will use default (typically
unbuffered) output when connected to a tty/pty.

This is why subprocess.Pope n() won't work with the following program when
stdout and stderr are pipes:

#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
for(i = 0; i < 5; i++)
{
printf("stdout ding %d\n", i);
fprintf(stderr, "stderr ding %d\n", i);
sleep(1);
}
return 0;
}

Then

subprocess.Pope n(cmd, stdout=subproce ss.PIPE, stderr=subproce ss.PIPE)

is read using polling, but the pipes don't return any data until the
program is done. As expected, specifying a bufsize of 0 or 1 in the Popen()
call has no effect. See end of mail for example Python scripts.

Unfortunately, changing the child program to flush stdout/err or specifying
setvbuf(stdout, 0,_IONBF,0); is an undesired workaround in this case.

I went with pexpect and it works well, except that I must handle stdout and
stderr separately. There seems to be no way to do this with pexpect, or am
I mistaken?

Are there alternative ways of solving this? Perhaps some way of

I'm on Linux, and portability to other platforms is not a requirement.

s
#Test script using subprocess:
import subprocess
cmd = '/tmp/slow' # The C program shown above
print 'Starting...'
proc = subprocess.Pope n(cmd, stdout=subproce ss.PIPE, stderr=subproce ss.PIPE)
while True:
lineout = proc.stdout.rea dline()
lineerr = proc.stderr.rea dline()
exitcode = proc.poll()
if (not lineout and not lineerr) and exitcode is not None: break
if not lineout == '': print lineout.strip()
if not lineerr == '': print 'ERR: ' + lineerr.strip()
print 'Done.'
#Test script using pexpect, merging stdout and stderr:
import sys
import pexpect
cmd = '/home/sveniu/dev/logfetch/bin/slow'
print 'Starting...'
child = pexpect.spawn(c md, timeout=100, maxread=1, logfile=sys.std out)
try:
while True: child.expect('\ n')
except pexpect.EOF: pass
print 'Done.'
Jun 27 '08 #1
1 3137
sven _ <sv******@gmail .comwrote:
In short: unless specifically told not to, normal C stdio will use
full output buffering when connected to a pipe. It will use default
(typically unbuffered) output when connected to a tty/pty.
Wrong. Standard output to a terminal is typically line-buffered.
(Standard error is never buffered by default, per the ISO C standard.)
This is why subprocess.Pope n() won't work with the following program
when stdout and stderr are pipes:
Yes, obviously.
I went with pexpect and it works well, except that I must handle
stdout and stderr separately. There seems to be no way to do this with
pexpect, or am I mistaken?
You could do it by changing the command you pass to pexpect.spawn so
that it redirects its stderr to (say) a pipe. Doing this is messy,
though -- you'd probably need to set the pipe's write-end fd in an
environment variable or something.

It's probably better to use os.pipe and pty.fork.

As mentioned above, the inferior process's output will still be
line-buffered unless it does something special to change this.

-- [mdw]
Jun 27 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
2334
by: pinbot | last post by:
As far as I know, http headers should not work after content has been written. This is how my production box is working, but for some reason on my dev box I was getting away with a location header after content (some debug notes) was written. Just to be sure, I threw a die() in right before the header('Location: '...) call, and sure enough there was the same stuff on screen that the live box is choking on. So does anyone have any...
1
2239
by: Shaun Jackman | last post by:
I'm reading from a tcpdump pipe. I want to receive one line from the pipe as soon as its available from tcpdump. Something is buffering the pipe though, so I am receiving nothing, then multiple lines in a big batch. I thought this was the inherent buffering of next(), but it affects readline too. For example, tcpdump = os.popen( 'sudo tcpdump', 'r') both while True: print tcpdump.next(),
2
1509
by: MiLoS | last post by:
I have an issue where I am sending back xml content using ASP. When I flush the buffer or turn the buffering off their seems to be a end tag that gets appended to the end of this response. There is no begin tag to match. In the trace I can simply see this tag added: 3C 2F 4D 65 73 73 61 67 65 3E </Message> Is this a setting somewhere in IIS or is this as designed ?? I have not been able to find a lot on this issue as...
1
5393
by: Oz | last post by:
This is long. Bear with me, as I will really go through all the convoluted stuff that shows there is a problem with streams (at least when used to redirect stdout). The basic idea is that my application (VB.NET) will start a process, redirect its stdout and capture that process' output, displaying it in a window. I've written a component for this, and a test application for the component. It allows me to specify a command to execute,...
7
15614
by: Mathias Herrmann | last post by:
Hi. I have the following problem: Using popen() to execute a program and read its stdout works usually fine. Now I try to do this with a program called xsupplicant (maybe one knows), but I dont get the output of it while it is running. This is probably a problem of stdout being buffered, because if I use fflush() after a printf() in the xsupplicant then I can read the output.
1
3937
by: Brian Henry | last post by:
In the documentation for the listview for owner drawn it says this Note To avoid issues with graphics flickering when owner drawing, override the ListView control and set the DoubleBuffered property to true. Now, I am owner drawing my list view items, and yes it does flicker a lot...
7
1580
by: charpour | last post by:
Hello, I am implementing a server in C using the select function and I have problems implementing a buffering system for holding client data until the client socket is available for reading/writing (sendq and receivq). What I am trying to do is "save" the data in the client's recvq right after data is availiable for the socket and write buffered data (sendq) to the socket when it's ready. The prog skeleton is like this:
11
1505
by: Peter Webb | last post by:
I previously asked about two problems I had with some graphics - the first was that when I drew animation to a picturebox it wouldn't display when the Form loaded. It was suggested to me by everyone that I stop using my own CreateGraphics calls, and override an OnPaint call to do this. As suggested, I created a custom control "drawBox" with an override on its OnPaint. Because I am using manual double buffering, as people suggested it was...
6
3811
by: Tim Arnold | last post by:
I have a bunch of processes to run and each one needs its own working directory. I'd also like to know when all of the processes are finished. (1) First thought was threads, until I saw that os.chdir was process- global. (2) Next thought was fork, but I don't know how to signal when each child is finished. (3) Current thought is to break the process from a method into a
0
9843
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9682
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10881
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10628
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9406
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7807
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7004
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5850
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4475
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.