[Tutor] Python popen command using cat > textfile .... how toterminate

Steve Willoughby steve at alchemy.com
Fri May 15 17:51:26 CEST 2009


On Fri, May 15, 2009 at 04:18:16PM +0100, Alan Gauld wrote:
> echo ^D | cat > foo
> 
> sends a CtrlD to cat which writes an empty file to foo.

And since this seems to be a point of confusion for you,
keep in mind that the ^D character itself is not a "command"
or even seen by the cat program at all.  So the notion of
"sending ^D to cat" via the interprocess pipe from Python
isn't really the right concept.  You never send ^D to cat.

When cat (or any program) is expecting input (say, from its
standard input device) which is coming from your terminal
(i.e., reading in whatever you're typing), then ^D is the
default character the *Unix I/O system* recognizes as 
signalling the end of input for that device.  This will cause
*the OS* to close that input device.  All the cat program sees
is that its input has run out of data.

The same is true on other OSes like VMS or DOS or Windows,
which use ^Z to mean the same thing (and note that even
on Unix you can assign a different key than ^D if you want
to).

That's why from Python, when you're not using the normal
TTY control support from the OS itself, but sending data
to cat from your Python program, there's no notion of ^D,
but you do the same thing to cat that the OS would do:
you close the input device.

I hope that makes it clearer.

> And all of them are a bad way to create an empty file in either *nix or 
> Python.

Very much so.  But don't feel bad, this is a very common 
mistake for beginners to make.  Cat has a number of uses it's
well suited for, but don't fall into the trap of using it for
everything when there are better tools available.  I seem to
keep running into people who do things like

  $ cat myfile | more

because they just learned the pattern "cat file |..." without
really learning how to use file redirection and how these things
work.

But more importantly, don't fall into the trap of launching
external programs to do simple tasks which are already built
into your language.  You just introduce extra code you don't
need, dependencies on the OS platform you don't need, and 
security and performance problems as an extra bonus.

> When working in Python, every time you are tempted to call
> a unix command via os.system/popen etc check to see if
> there is a way to do it from within python fiorst.
> There often is.

Almost always.  Plus, if you do it in Python your program
will work on Windows.  And MacOS.  And VMS.  And a Unix
system where the user has a "cat" program which behaves
differently than yours does... which trying to call 
"cat" yourself won't.

 
> HTH,

HAND,

-- 
Steve Willoughby    |  Using billion-dollar satellites
steve at alchemy.com   |  to hunt for Tupperware.


More information about the Tutor mailing list