By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,767 Members | 1,334 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,767 IT Pros & Developers. It's quick & easy.

execute shell command pipeline

P: n/a
Hi,

I'm a Python newbie and I'm wondering how I can do the following Perl thing:

open(F, 'grep -b 2004 logfile | head -1 | cut -d: -f1 |') or die "blah, blah";
$offset = <F>;
( or $offset = `grep -b 2004 logfile | head -1 | cut -d: -f1`; )

in Python. When I tried:

offset = os.popen('grep -b 2004 logfile | head -1 |cut -d: -f1').read()

I get a whole bunch of error messages --

grep: writing output: Broken pipe

Any help would be most appreciated.

Regards,

Paul
Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
In article <87**************************@posting.google.com >,
Paul <Pa******@telus.com> wrote:
Hi,

I'm a Python newbie and I'm wondering how I can do the following Perl thing:

open(F, 'grep -b 2004 logfile | head -1 | cut -d: -f1 |') or die "blah, blah";
$offset = <F>;
( or $offset = `grep -b 2004 logfile | head -1 | cut -d: -f1`; )

in Python. When I tried:

offset = os.popen('grep -b 2004 logfile | head -1 |cut -d: -f1').read()

I get a whole bunch of error messages --

grep: writing output: Broken pipe

Jul 18 '05 #2

P: n/a
The Python library manual says (http://python.org/doc/lib/module-signal.html)
Python installs a small number of signal handlers by default: SIGPIPE
is ignored (so write errors on pipes and sockets can be reported as
ordinary Python exceptions) and SIGINT is translated into a
KeyboardInterrupt exception. All of these can be overridden.
In perl, or from the shell, grep is terminated by SIGPIPE. In Python,
grep ignores the signal because the "ignored" status of SIGPIPE is
inherited by the child process. Instead, it prints the error once for
each write that returns -EPIPE.

Jeff

Jul 18 '05 #3

P: n/a
Paul wrote:
Hi,

I'm a Python newbie and I'm wondering how I can do the following Perl thing:

open(F, 'grep -b 2004 logfile | head -1 | cut -d: -f1 |') or die "blah, blah";
$offset = <F>;
( or $offset = `grep -b 2004 logfile | head -1 | cut -d: -f1`; )

in Python. When I tried:

You don't have to do it this verbosely, but it works:

import os
text = '2004'
filename = 'logfile'
delim = ':'
matches = os.popen('grep -b %s %s' % (text, filename)).readlines()
if matches:
first = matches[0]
offset = first.split(delim)[0]
# note: offset is now a string

// m

Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.