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

Alan Gauld alan.gauld at btinternet.com
Fri May 15 17:18:16 CEST 2009


"MK" <lopoff at gmx.net> wrote

> Seems that i did it the wrong way still from the beginning.
> I did it now with open and write an empty file.
>
> But anyway i would wish to know if it is possible to terminate
> a running cat.

It depends on what you mean by a running  cat.

cat simply concatenates (ie joins) its input to its output.
By default cat's input is stdin and its output is stdout
so if you just type cat anything you type on stdin gets
echoed to stdout. You terminate the command by
inputing an EOF character (Ctrl D on *nux)

cat > foo

writes stdin to foo
Again, to terminate it you send EOF via stdin.
So if you use subprocess/popen to run cat you need
to write EOF to the stdin port. You can do that with
popen2 or subprocess.Popen but not with simple
popen which only lets you read stdout.

cat > foo < /dev/null

writes the non file at dev/null to foo and since that
has an implicit EOF it terminates automatically

echo ^D | cat > foo

sends a CtrlD to cat which writes an empty file to foo.

Your questions are simply about how to run cat not
about Python. Any/All of the above can be run from
Python.

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

In *nix use touch and in Python use

open(foo,'w').close()

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.


HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/ 




More information about the Tutor mailing list