[Tutor] NEWBIE!! pipes

Kalle Svensson kalle@gnupung.net
Thu, 1 Feb 2001 20:52:05 +0100


--Yylu36WmvOXNoKYn
Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

Sez AquaRock7@aol.com:
> What are pipes?  The docs barely touched this subject, it assumed you alr=
eady=20
> knew what they are...  From context I am gathering that it is a connectio=
n to=20
> the kernel?  (maybe?)  How can I utilize this?

It is much like a file, but it's connected to another program.  The name is
actually pretty telling, your program holds one end of the pipe and the
other program holds the other.  If you put something in, it comes out in the
other end, and vice versa.  Computer pipes are one-way though, either you
have a write pipe or a read pipe (I think?).
Anyway, they're really cool to have in a shell:
ps ax | grep netscape | grep -v grep | awk '{ print $1 }'
is a common command on UNIX workstations, it finds the process id of
netscape, to be able to kill it when it's sucking all the CPU again.

In python, the most common way to use pipes is the os.popen* family of
functions.  They return pipes to/from a process.
Artificial example:
>>> import os
>>> inpipe =3D os.popen("ls")
>>> outpipe =3D os.popen("lpr", "w")
>>> outpipe.write(inpipe.read())
>>>
should print the contents of the current directory to your printer.
Better examples for windows are left for others to figure out.

> 1 more quickie:
> >if __name__ =3D=3D '__main__':
> >     main()
>=20
> what is the pourpose if the above code?  It runs the sub main() (duh :) b=
ut,=20
> why not just main() wihtout the if?  what is the conditional testing for?=
 =20
> and what are the variables __main__ and __name__?  i dont believe they ar=
e=20
> defined in the program, so just what are they?  and, what does putting "_=
_"=20
> around a variable actually DO besides look cool ?

Good questions!  Variables with "__"s around them are system variables,
often automatically defined by the system.  Every module has a __name__, and
when it is run directly from command line, this is "__main__".
>>> import cgi
>>> cgi.__name__
'cgi'
>>> print __name__
__main__
>>>=20

Thus
if __name__ =3D=3D '__main__':
    main()

only runs main() if the file is run, as opposed to imported from another
module.  This enables modules to work both as libraries and programs at the
same time.  Great, huh?

HTH,
  Kalle
--=20
Email: kalle@gnupung.net     | You can tune a filesystem, but you
Web: http://www.gnupung.net/ | can't tune a fish. -- man tunefs(8)
PGP fingerprint: 0C56 B171 8159 327F 1824 F5DE 74D7 80D7 BF3B B1DD

--Yylu36WmvOXNoKYn
Content-Type: application/pgp-signature
Content-Disposition: inline

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.4 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE6eb5ldNeA1787sd0RAuoaAKCwtRdr/rNm+c/7K2bBg7yTh/Q/TQCeIgkP
UVp6rNv78hCuE5Ata03Ng1g=
=pjlL
-----END PGP SIGNATURE-----

--Yylu36WmvOXNoKYn--