473,685 Members | 2,996 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sys.stdin.readl ine()

When I invoke readline() in a for loop, why does it return a series of
one-char strings, rather than the full line?
for sL in sys.stdin.readl ine(): print sL

....
abc
a
b
c

(I typed in 'abc', and the loop printed out 'a\nb\nc\n')

I.e. how can I make readline() wait for the newline before returning a
value? 'readline()' seems to be acting exactly like 'read()' here.

('readlines()' works fine in this context, except that it waits for
eof; I'd really rather iterate over lines in stdin as they come in)
Jul 18 '05 #1
12 53298
On 2004-08-31, Mike Maxwell <ma*****@ldc.up enn.edu> wrote:
When I invoke readline() in a for loop, why does it return a series of
one-char strings, rather than the full line?
for sL in sys.stdin.readl ine(): print sL
...
abc
a
b
c

(I typed in 'abc', and the loop printed out 'a\nb\nc\n')

I.e. how can I make readline() wait for the newline before returning a
value?


It is.
'readline()' seems to be acting exactly like 'read()' here.


Sort of.

What you want is:

import sys
while True:
s = sys.stdin.readl ine()
if not s:
break
print s

--
Grant Edwards grante Yow! .. I see TOILET
at SEATS...
visi.com
Jul 18 '05 #2
Mike Maxwell wrote:
When I invoke readline() in a for loop, why does it return a series of
one-char strings, rather than the full line?
for sL in sys.stdin.readl ine(): print sL


It does return a full line. *One* line. Then your loop iterates
over the characters in that line.

Try `for sL in sys.stdin.xread lines(): print sL'.
Or in newer Pythons, simply `for sL in sys.stdin: print sL'.

--
Hallvard
Jul 18 '05 #3
Hallvard B Furuseth <h.b.furuseth <at> usit.uio.no> writes:
Or in newer Pythons, simply `for sL in sys.stdin: print sL'.


This doesn't work for me in the interactive shell:

Python 2.4a2 (#55, Aug 5 2004, 11:42:43) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright" , "credits" or "license" for more information.
import sys
for l in sys.stdin:

.... print repr(l)
....
A
B
C
D
^Z
'A\n'
'B\n'
'C\n'
'D\n'

Note that I don't get output until I hit ^Z (this is, obviously, a Windows
box). I tried starting Python with the -u option too, and I still get this
result. Is there any way to make 'for l in sys.stdin' work the way you
suggest it does at an interactive prompt?

Steve

Jul 18 '05 #4
Steven Bethard wrote:
Hallvard B Furuseth <h.b.furuseth <at> usit.uio.no> writes:
Or in newer Pythons, simply `for sL in sys.stdin: print sL'.
This doesn't work for me in the interactive shell:
(...)


Whoops - you just found a mysterious bug in a program I'm writing.
Thanks:-)
Note that I don't get output until I hit ^Z (this is, obviously, a Windows
box). I tried starting Python with the -u option too, and I still get this
result. Is there any way to make 'for l in sys.stdin' work the way you
suggest it does at an interactive prompt?


Can't see any in the manual, now that I've looked more closely.
Info node "(python-lib)File Objects" says file.next() uses a read-
ahead buffer. It doesn't say one can disable that.

--
Hallvard
Jul 18 '05 #5
Hallvard B Furuseth wrote:
Mike Maxwell wrote:
When I invoke readline() in a for loop, why does it return a series of
one-char strings, rather than the full line?
>for sL in sys.stdin.readl ine(): print sL

It does return a full line. *One* line. Then your loop iterates
over the characters in that line.


LoL, thanks!
Try `for sL in sys.stdin.xread lines(): print sL'.
Or in newer Pythons, simply `for sL in sys.stdin: print sL'.


I think I saw that, but when I tried it, I got:

/lib/python2.3/pydoc.py:250: DeprecationWarn ing:
xreadlines is deprecated; use 'for line in file'.

--which got me off on this dead end.

What I was originally trying to do, is to implement a one-liner that
would act something like 'sed', but applying to Unicode characters. An
example would have a command that looked something like
"s/u'\u0D0A'//"
i.e. delete all instances of the Unicode char U+0D0A (which you can't do
with 'sed', at least not the version that I'm using).

The guy down the hall does these kinds of things with perl one-liners,
but I have more dignity than to use perl... Unfortunately, it's looking
more and more complex to do one-liners like this in Python. Am I
overlooking s.t.?

Mike Maxwell
Jul 18 '05 #6
Mike Maxwell <ma*****@ldc.up enn.edu> wrote:
...
The guy down the hall does these kinds of things with perl one-liners,
but I have more dignity than to use perl... Unfortunately, it's looking
more and more complex to do one-liners like this in Python. Am I
overlooking s.t.?


No, I think you're correctly observing that Python isn't oriented to
one-liners -- not at all. Most interesting things in Python require
more than one line. You could write a "oneliners shell" that takes some
defined separator and turns it into a newline, of course, e.g.:

bangoneliner.py :
#!/usr/bin/env python
import sys
oneliner = sys.argv.pop(1)
exec '\n'.join(oneli ner.split('!'))

now, sometying like

bangoneliner.py 'for x in xrange(7):! if x%2:! print x'

should work (note that inserting the spaces after the bangs to simulate
proper indentation IS a silly fuss, but you hafta...:-).
Alex
Jul 18 '05 #7
Alex Martelli wrote:
Mike Maxwell <ma*****@ldc.up enn.edu> wrote:
No, I think you're correctly observing that Python isn't oriented to
one-liners -- not at all. Most interesting things in Python require
more than one line.
<rant>
I don't care whether it's "interestin g", I just want to get some work
done. And since most of the text processing tools in Unixes that I
would otherwise use (grep, sed, tr) don't support Unicode, and are
inconsistent in their regular expression notation to boot, it would be
nice if I could write regex operations in a single, consistent
programming language. Python is a single, consistent programming
language, but as you say, it doesn't lend itself to one-liners.
</rant>
You could write a "oneliners shell" that takes some
defined separator and turns it into a newline, of course, e.g.:

bangoneliner.py :
#!/usr/bin/env python
import sys
oneliner = sys.argv.pop(1)
exec '\n'.join(oneli ner.split('!'))

now, sometying like

bangoneliner.py 'for x in xrange(7):! if x%2:! print x'

should work
Hmm, I may give that a try...thanks!
note that inserting the spaces after the bangs to simulate
proper indentation IS a silly fuss, but you hafta...:-).


Well, I guess I could translate some other char (one that's easier to
count than spaces) into indents, too.

Mike Maxwell
Jul 18 '05 #8
Mike Maxwell <ma*****@ldc.up enn.edu> wrote:
Alex Martelli wrote:
Mike Maxwell <ma*****@ldc.up enn.edu> wrote:
No, I think you're correctly observing that Python isn't oriented to
one-liners -- not at all. Most interesting things in Python require
more than one line.
<rant>
I don't care whether it's "interestin g", I just want to get some work
done.


Something that lets you get work done IS thereby interesting. Most
interesting things in Python require more than one line. So, I don't
see the basis for your rant.
And since most of the text processing tools in Unixes that I
would otherwise use (grep, sed, tr) don't support Unicode, and are
inconsistent in their regular expression notation to boot, it would be
nice if I could write regex operations in a single, consistent
programming language. Python is a single, consistent programming
language, but as you say, it doesn't lend itself to one-liners.


No, but a supporting script similar to the one I suggest below can
easily be adapter to offer more sensible functionality than any oneliner
might sensibly support -- for example (for the kinds of tasks you imply)
by including and automatically using such modules as re and fileinput.
now, sometying like

bangoneliner.py 'for x in xrange(7):! if x%2:! print x'

should work


Hmm, I may give that a try...thanks!


You're welcome.

note that inserting the spaces after the bangs to simulate
proper indentation IS a silly fuss, but you hafta...:-).


Well, I guess I could translate some other char (one that's easier to
count than spaces) into indents, too.


Sure, or you could use (e.g.) '!3' to translate into 'newline then three
spaces', or use block start/endmarkers and translate them into
indents/dedents, etc, etc.

Personally, given your now-restated problem, that you need 'better'
versions of grep, sed and tr, I would take another tack -- I would
reimplement _those_ in Python with its re sublanguage and Unicode
support. Using them should be easier and tighter than putting newliners
together, I think.
Alex
Jul 18 '05 #9
Mike Maxwell wrote:
Alex Martelli wrote:
Mike Maxwell <ma*****@ldc.up enn.edu> wrote:
No, I think you're correctly observing that Python isn't oriented to
one-liners -- not at all. Most interesting things in Python require
more than one line.


<rant>
I don't care whether it's "interestin g", I just want to get some work
done. And since most of the text processing tools in Unixes that I
would otherwise use (grep, sed, tr) don't support Unicode, and are
inconsistent in their regular expression notation to boot, it would be
nice if I could write regex operations in a single, consistent
programming language. Python is a single, consistent programming
language, but as you say, it doesn't lend itself to one-liners.
</rant>


Most of us who do this conclude that our potential one-liner
is actually likely to be re-used, and we write the Python
three-liner equivalent in a file. Later on, we typically find
that it has grown to seventeen lines and we don't particularly
mind the slight extra inconvenience of having to put the
initial code in a file instead of trying to retype it each
time we need it.

-Peter
Jul 18 '05 #10

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

Similar topics

0
2394
by: Brano Zarnovican | last post by:
Hi ! I'd like to init curses and still have working Python interactive command line. I found that you can replace stdin/stdout/stderr like this: #!/usr/bin/python -i import curses import sys
6
2782
by: Christian Convey | last post by:
Hello, I've got a program that (ideally) perpetually monitors sys.stdin for lines of text. As soon as a line comes in, my program takes some action. The problem is, it seems like a very large amount of data must accumulate on sys.stdin before even my first invocation of readline() returns. This delay prevents my program from being responsive in the way it must be.
1
3257
by: Benjamin Rutt | last post by:
There has been a problem that has been bugging me for a while for reading input from standard in. Consider the following simple program: #!/usr/bin/env python import sys print 'enter something: ', answer = sys.stdin.readline().strip() print 'you answered {%s}' % (answer) When I run this interactively, the following happens:
1
11165
by: ywzhan | last post by:
Hi, I am new here. When I use sys.stdin.readline() to get input string from user, how can I set a timeout value for this operation? thank you.
8
3811
by: Christoph Haas | last post by:
Hi... I encountered a problem that - according to my google search - other people have found, too. Example code: import sys for line in sys.stdin: print line Running this code in Python 2.3 or 2.4 has the problem that I need to
25
5845
by: 7stud | last post by:
I can't break out of the for loop in this example: ------ import sys lst = for line in sys.stdin: lst.append(line) break
4
3566
by: joamag | last post by:
HI, Is there any possible way to unblock the sys.stdin.readline() call from a different thread. Something like sys.stdin.write() but that would actually work ... something to put characters in the stdin... Thanks in advance, João
0
1430
by: Jean-Paul Calderone | last post by:
On Sat, 21 Jun 2008 12:35:02 -0700 (PDT), joamag <joamag@gmail.comwrote: Twisted supports asynchronous handling of stdin on both POSIX and Windows. See stdiodemo.py and stdin.py under the Miscellaenous section at http://twistedmatrix.com/projects/core/documentation/examples/ Jean-Paul
2
4420
by: Grant Edwards | last post by:
I'm trying to figure out how to use the gnu readline library so that when my program is prompting the user for input there is line editing and history support. I've read and re-read the documentation for the "readline" module in the standard library and I still can't figure out how to use the module or even if the module is intended to do what I want. The example code all seems to be about on how to modify the behavior of an...
0
8577
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
8507
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
8773
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7589
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
6431
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
5792
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
4523
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1927
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.