Mailing List Archive

Python to Perl Conversions
Per your collective requests, here is one of the documents
with my collective observations from learning Python.

Some have mentioned that I've left things out that are in
more recent releases. I'm sorry, but I only have Mark Lutz's
book to go on. There are no manpages for Python. Like most
people, I'll wait until the next edition of the book is release
rather than digging around elsewhere if the manpage are missing.

This article was posted to the Perl newsgroup, but I have duplicated
the posting here without crossposting to avoid flame wars.

--tom

+-----------------------+
| Operations on numbers |
+-----------------------+

Python Construct Perl Equivalent
===========================================================================
x + y + for numbers, . for strings, and
interopolation for arrays (@a, @b)
and hashes (%a, %b)

x - y same

x * y * for numbers, x for strings and lists.

x / y Same for floats, but Perl doesn't do
integer division here usually. Python
things 3/4 is 0 (and false), but 3.0/4.0 is 0.75

x % y same; Perl and Python use the same
definition of modulus, even though this
differs from that of C with respectd to
negative operands.

abs(x) same

int(x) same, except perl only requires it for
truncation toward zero, and python
needs it all over the place, since
strings aren't numbers, nor are they
autoconverted.

long(x) These are bignums, not C longs, so:
use Math::BigInt;
$n = Math::BigInt->new(expr);

float(x) not applicable

divmod(x,y) no direct equiv; same as
( int($x / $y), $x % y )

pow(x,y) x ** y

x | y, x ^ y, x & y same, although python's only work on ints
and its bignum longs and blow up
on floats, and perl's don't work on
Math::BigInts, but do work on strings in
a very different way, and truncate floats.

x << n, x >> n same, although Perl works differently if
you go over 31 bits: Python keeps giving
you 0, whereas Perl wraps. 1<<34 is 0 in
python but 4 in perl.

~x same-ish, but see |&^ above for details.
In particular, you can't negate bitstrings
in python.

===========================================================================

+----------------------------+
| Operations on dictionaries |
+----------------------------+

Python Construct Perl Equivalent
===========================================================================

len(d) keys %d, in a scalar context; e.g.:
$count = keys %ENV;

d[k] "same": $h{$k} as a real %hash, and
$hr->{$k} as a reference

d[k] = x "same":
$h{$k} = x; # real %hash
$href->{$k} = x; # as reference
Note that Python doesn't support hash
slices, which in Perl are simple:
@hash{k1,k2,k3} = (v1, v2, v3)

del d[k] delete $h{$k}, but Python can't do more
than one at a time on a hash, as in Perl's
delete @hash{k1,k2,k3}

d.items() Just use %hash in list context to get all
the key/value pairs as a flat list.

d.keys() keys %hash

d.values() values %hash

d.hash_key(k) exists $hash{k}

===========================================================================

+--------------------------------------------------+
| Operations on sequences (strings, tuples, lists) |
+--------------------------------------------------+

x in s No built-ins, must use grep or loop.
Lists/arrays: grep { $x == $_ } @s
Strings: index($s, $x) != 0

x not in s See previous entry.
Lists/arrays: !grep { $x == $_ } @s
Strings: index($s, $x) < 0

for n in x for $n (@array) # arrays
for $c (split //, $string) # strings

s + s $s . $s

s * n, n * s $s x $n for strings and lists/arrays, but
must be in that order in Perl. Python
allows the number in either place.

s[i] $array[i] for arrays, but
substr($s, $i, 1) for strings

s[i:j] @array[ $i .. ($j - 1) ] for arrays, but
substr($s, $i, $j - 1) for strings. Yes,
slices in python don't include the
termination point.

len(s) @array in a scalar context for arrays, e.g.
$count = @array;
but length($s) for strings.

min(s), max(s) no equivalent in core perl, so you'd need a
loop, although the CPAN module builtin.pm
provides these in fast C code.

===========================================================================

+---------------------+
| Operations on lists |
+---------------------+

s[i] = x $a[i] = expr, but Perl can do this even if
the array isn't long enough yet, and Python
can't. You have to grow it with the append
method below.

s[i:j] = x @a[. i .. (j - 1) = list_expression
but see above. Also, Perl's slices needn't
be contiguous, and Python's must. Yes, slices
don't include endpoint in Python.

del s[i] splice(@a, i, 1)

del s[i:j] splice(@a, i, j - 1) for values of i and j.
Yes, slices don't include endpoint in Python.

s.append(x) push(@array, listexpr)

s.count(x) grep { $_ == expr } @array (for numbers)
grep { $_ eq expr } @array (for strings)
grep { /expr/ } @array (for patterns)

s.index(x) no direct equivalent, need loop:
$found = undef;
for $i ( 0 .. $#array ) {
if ($array[$i] == expr) { # numeric
$found = $i;
last;
}
}

s.insert(i,x) splice(@array, $i, 0) = x;

s.remove(x) this deletes the first x in s, and has no
direct equivalent. the simple
@a = grep { !/x/ } @a
deletes all of them, but as a pattern. For
the first, you'd need a loop or extra
variable, because grep doesn't shortcircuit.
$found = 0;
@a = grep { !/x/ || !$found++) } @a;
or as a string
$found = 0;
@a = grep { $_ ne x || !$found++ } @a;

s.reverse @a = reverse @a; note that python's reverse
is in-place *only*, and doesn't work on
character strings.

s.sort(cmp?) Noting that Python's sort is in-place only, use
@a = sort @a;
@a = sort some_cmp @a;


===========================================================================

+--------------------+
| built-in functions |
+--------------------+

apply(fn,args) &fn(@args) will skip prototype checks that
fn(@args) would normally enforce. In
general, perl doesn't need this at all,
because indirect function calls don't do
prototype checks.
$name = "fn"; # or \&fn
$name->(@arglist)

callable(x) n/a or else UNIVERSAL::isa($x, "CODE")

chr(i) same

cmp(x,y) x cmp y

coerce(x,y) n/a!

compile(string,label,kind) $coderef = eval "sub { $string }"

delattr(object,name) n/a? "delete named attribute from object".
I suppose this might be
delete $obj->{name}
but that's pretty uncool to do it without
asking the object.

dir(object) n/a for most. returns a list of attribute
names in object or the caller's local scope.
for modules, you can do
keys %module::
and for hash-based objects,
keys %$obj
But you can't get the local (lexical
my variables) names in Perl without
resorting to C code.

eval(code) Same as Perl, but Perl's handles
statements, and python's only handles
expressions. Also, python hurls an
exception if it doesn't like you,
whereas Perl sets $@. People use this
to convert string to numbers. This is
a terrible security hazard.

exec(code) eval(code); plus see previous entry.

execfile(file) do 'file'; plus see anteprevious entry.

filter(func,list) grep { func($_) } list

getattr(obj,name) n/a? maybe just $obj->{$name}. I don't
understand why this exits. Oh heck, yes I
do. Because you can say
name = "widget_count"
obj.name
Because there's no interpolation and
otherwise it will look up name. Oh my.
This is like the apply() mess.

globals() keys %{ __PACKAGE__ . "::" }

hasattr(obj,name) exists $obj->{$name}

hash(x) huh? "returns the hash value of the object,
if any"

hex(n) sprintf("%#x", n)
Perl's hex() function is the opposite.
It converts 22 into 37. Python's hex
function converts 37 into 0x22. Oh my!

id(obj) Just use $obj in numeric context. "returns
the unique id for the object, its addr in memory"

input(prompt?) n/a. This reads and evals the input
stream! Needed because otherwise you can't
read a number. Or you could read the
string and convert it. Ick. Security
hazard waiting to happen.

locals() n/a. We can't get our block's lexicals
without resorting to C. And even if
we hand them, we can't symbolically
dereference they're names, since the
package (module's global) symbol table
is completely separate from that of the
lexicals' (local) one, and sym deref
only does the former.

map(fn, list) map(fn($_), list) # or written
map { fn($_) } list
Except Perl's map won't parallelize, as in
map(fn, [1,2,3], [4,5,6])
will call fn() thrice, as in
fn(1,4)
fn(2,5)
fn(3,6)
Note that Perl's map doesn't have to be
function; it can just be a code block.
@trips = map { 3 * $_ } @singles;

oct(n) sprintf("%#o", $n)
Like hex, Python has this completely
backwards. Python's oct(44) returns 054,
but Perl's oct(44) return 36. UG!

open(path,mode) Perl's open function works very differently.
$success = open(FH, mode . path)

ord(c) same

range(start?, end, step?) Either use a range operator, but be careful
of the end point:
@nums = $start .. ($end - 1)
or a for() loop
for ($i = $start; $i < $end; $i += $step)
or even
for $i ( $start .. ($end - 1) )

raw_input(prompt?) print "prompt";
$line = <STDIN>;
chomp($line); # but perl groks RS

reload(module) First delete from %INC, then require the
module again, as in:
delete $INC{"Module.pm"}
require Module;
Note that Python doesn't directly support
nested modules as in
require Dir1::Dir2::Dir3::Module;
except via a disgustingly named hackaround
module.

repr(x) "$x". Python also use `x` for this.

setattr(obj,name,value) $obj->{$name} = $value;
Interpolation wins again. See getattr.

str(x) I thought this was the same as repr().

tuple(seq) n/a. This is a nasty hack to deal with the
fact that (1,2,3) is different from [1,2,3].
Hm... maybe it's like this:
$aref = [1,2,3];
@list = @$aref;

type(obj) ref($obj) returns its string type

vars(obj) n/a, maybe. keys %$obj, but not really
anything for the locals.

xrange ... Like range, but avoids generating all at
once as Python's
for i in range(100000):
would. Perl's solution was to fix
for $i (1 .. 99999)
instead to do lazy evaluation.

===========================================================================

+--------------+
| file methods |
+--------------+

s = file.read(size?) $bytes_read = read(FH, $s, $size)
Perl's read() doesn't let you leave
off the last argument to mean "read all".
Usually, you undefined your input record
separator and use readline for that.

file.readline() $s = readline(*FH)
or more commonly
$s = <FH>

file.readlines() @a = readline(*FH)
or more commonly
@a = <FH>

file.write(string) print FH "string"

file.writelines(list) print FH @array_of_lines

file.close() close(FH)

file.tell() tell(FH)

file.seek(offset,whence) seek(FH, offset, whence)

file.isatty() -t FH

file.flush() Either FH->autoflush(1) if you're using the
aliasing modules, or else the klunky but
fast:
$old_fh = select(FH);
$| = 1;
select($old_fh);
Note that this just sets autoflushing
on each subsequent output on that handle.

===========================================================================

+------------------------------------------------------------+
| sys library. There aren't there unless you have imported |
| the library module via "import sys". |
+------------------------------------------------------------+

sys.argv @ARGV but sys.argv[1] in Python
is $ARGV[0] in Perl, and sys.argv[0]
in Python is $0 in Perl, which is mutable.

sys.builtin_module_names You either recursively go through %main::,
or look at %INC. But these only show what
was loaded, not what was built in.

sys.exc_type n/a or $@. Perl doesn't have even
loosely typed exceptions, just strings.
There is support for exception objects,
but people don't use them.

sys.exc_value The $@ variable, mostly. See previous
entry.

sys.exc_traceback n/a or $@. We have no exception
traceback object. Traceback gets appended
to value.

sys.exit(status) exit(status) and no import is bloody
necessary just to leave the program.
But that Python does this by raising
a SystemExit exception. Perl can use
END{} handlers to catch these and do
at-exit processing, and Python doesn't.
You have to roll your own.

sys.exitfunc This is one function to call on normal exit
(not exception exits, unlike perl).
It would have to manage all the handlers
in your roll-your-own scheme. Very ugly.

sys.getrefcount(object) This isn't exposed in Perl, save through the
standard Devel::Peek module.

sys.last_type n/a. Type of last unhandled exception.

sys.last_value n/a. Value of last unhandled exception.

sys.last_traceback n/a. Traceback of last unhandled
exception.

sys.modules %INC

sys.path @INC

sys.platform $^O # that's a ^ and an O
You can use the $OSNAME alias from the
std English module if you like.

sys.ps1, sys.ps2 n/a. interactive prompts.

sys.setcheckinterval(reps) n/a. This is some event hook processing
thing.

sys.settrace(fn) n/a. set system traceback function. I
guess you could play with the Carp module.

sys.setprofile n/a; the profiler is separate in perl

sys.stdin STDIN

sys.stdout STDOUT

sys.stderr STDERR

sys.tracebacklimit n/a

===========================================================================

+---------------------------------------------------------------+
| string library. There aren't there unless you have imported |
| the library module via "import string". |
+---------------------------------------------------------------+

string.atof(s) n/a - Perl doesn't need this. Just use
the string as a float, and it is one.

string.atoi(s) n/a - Perl doesn't need this. Just use
the string as a int, and it is one.

string.atol(s) Perl doesn't have built-in bignums.
use Math::BigInt;
$n = Math::BigInt->new($s)

string.expandtabs(s,tabsize) From a module:
use Text::Tabs;
$tabstop = 4;
@without_tabs = expand(@with_tabs);

string.find(s,sub,start?) index(s,sub,start?) # no import

string.rfind(s,sub,start?) rindex(s,sub,start?) # no import

string.index(s,sub,st) if (index(s,sub,st) < 0) {die "ValueError"}

string.rindex(s,sub,st) if (rindex(s,sub,st) < 0) {die "ValueError"}

count(s, sub, start?) You use a loop or a pattern match:
$count = 0;
$start = 0;
while (($pos=index($s, $sub, $start) >= 0){
$count++;
$start += $pos;
}
Or with regex:
@matches = $s =~ /sub/g;
$count = @matches; # get scalar count
Or shorter:
$count = () = $s =~ /sub/g;
If you don't want regex magic chars, use
$count = () = $s =~ /\Qsub/g;

string.split(s) @a = split(' ', $s) # no import

string.splitfields(s,sep) @a = split(/sep/, $s) # no import
If you don't want regex magic chars:
@a = split(/\Qsep/, $s)

string.join(x) $s = join(" ", @x); # no import

string.joinfields(x, sep) $s = join($sep, @x); # no import

string.strip(s) Use two substs:
$string =~ s/^\s+//;
$string =~ s/\s+$//;
Or combined for legibility and
extensibility:
for ($string) {
s/^\s+//;
s/\s+$//;
}

string.swapcase(s) $s =~ tr[a-zA-Z][A-Za-z]
Except this isn't locale-aware.

string.upper(s) uc($s) # no import

string.lower(s) lc($s) # no import

string.ljust(s,width) sprintf("%*s", -$width, $s)
(no import), or use printf(), or use
format and write statements.

string.rjust(s,width) sprintf("%*s", $width, $s)
(no import), or use printf(), or use
format and write statements.

string.center(s,width) Easiest with format and write. Could
hack up a (s)printf otherwise.

string.zfill(s,width) sprintf("%0${width}d", $s)

===========================================================================

+-------------------------------------------------------------+
| POSIX library. These aren't there unless you have imported |
| the library module via "import posix". |
+-------------------------------------------------------------+

posix.environ The %ENV hash; no import needed in Perl.
However, assignment doesn't appear
to propagate to unborn children as
it does in Perl.

posix.error This might be Perl's $! errno
variable, but I'm dubious.
Failed syscalls in python always
raise an exception.

posix.chdir(path) chdir(path) # no import in Perl
Return value is success in Perl --
no exception raised on failure.

posix.chmod(path, mode) chmod(path, mode) # no import in Perl
Return value is success in Perl --
no exception raised on failure.

posix.chown(path,uid,gid) chown(path,uid,gid) # no import in Perl
Return value is success in Perl --
no exception raised on failure.

posix.close(fd) POSIX::close(fd); # real int, not stdio
Return value is success in Perl --
no exception raised on failure.

posix.dup(fd) POSIX::dup(fd), or just use open as
shown below

posix.dup2(fd, fd2) POSIX::dup2(fd, fd2), or just use the
basic open with its funky dup syntax:
open(HANDLE2, "<&$fd")

posix.execv(path,args) exec path, args; # no import in Perl

posix.execve(path,args, env) Just set your %ENV and then exec().

_exit(n) POSIX::_exit(n)

fdopen .... Use POSIX::fdopen or funky open:
open(HANDLE2, "<&=$fd")

posix.fork() fork() # no import
Return value is success in Perl --
no exception raised on failure.

posix.fstat() stat(HANDLE) # no import

posix.getcwd() use Cwd; $here = getcwd();
but most folks use `pwd` in perl

posix.getegid $) # not a typo

posix.getpid() $$ # not a typo

posix.kill(pid,sig) kill(sig,pid) # no import
In perl, a string is ok
kill("TERM", $$); # suicide
Or multipids
kill("HUP", $him, $her, @them)
Return value is success in Perl --
no exception raised on failure.

posix.link(src,dst) link($src,$dst) # no import
Return value is success in Perl --
no exception raised on failure.
I'll stop saying this now.

posix.listdir(path) opendir(DH, path);
readdir(DH); # no import

posix.lseek(fd,pos,how) seek(HANDLE, pos, how) # stdio
sysseek(HANDLE, pos, how) # no stdio
If you only have an fd, use
POSIX::seek() or fdopen it

posix.lstat(path) lstat(path) # no import

mkdir(path,mode) mkdir(path,mode) # no import

open(path,flags,mode) sysopen(HANDLE,path,flags,mode)
no import of posix needed except
for flags. use Fcntl is more
widely supported for this.

(f1,f2) = posix.pipe() pipe(FH1, FH2) # no import

fd = posix.popen(cmd,mod,bufsiz) No import. Just use regular open.
open(FH, "| cmd") # writing
open(FH, "cmd | ") # reading

posix.read(fd,n) POSIX::read or sysread() or usually
just regular read()

posix.readlink(path) readline(path) # no import

posix.rename(src,dst) rename(src,dst) # no import

posix.rmdir(path) rmdir(path) # no import

posix.setgid(id) $) = id # not a typo

posix.stat(path) stat(path) # no import
But if the list return is icky, you
can use the File::stat module to
get by-name object values.

posix.symlink(src,dst) symlink(src,dst) # no import

posix.system(cmd) system(cmdstr) # no import
Perl also a shell-safe version:
system(arglist)

posix.times() times() # no import

posix.umask(mask) umask(mask) # no import

posix.uname() POSIX::uname()

posix.unlink(path) unlink(path) # no import
perl also allows a list
unlink(f1,f2,f3)

posix.utime ... utime... # no import

posix.wait() wait() # no import

posix.waitpid(...) waitpid(...) # no import

posix.write(fd,str) use syswrite() normally,
or maybe POSIX::write


===========================================================================
--
If you consistently take an antagonistic approach, however, people are
going to start thinking you're from New York. :-)
--Larry Wall to Dan Bernstein in <10187@jpl-devvax.JPL.NASA.GOV>
Python to Perl Conversions [ In reply to ]
Tom Christiansen <tchrist@mox.perl.com> writes:

| Some have mentioned that I've left things out that are in more
| recent releases. I'm sorry, but I only have Mark Lutz's book to go
| on. There are no manpages for Python. Like most people, I'll wait
| until the next edition of the book is release rather than digging
| around elsewhere if the manpage are missing.

I realize they're not manpages per se, but if you haven't already taken a
look at the online documentation at <http://www.python.org/doc/current/>,
you should check it out. It has a lot of manpage-type information,
although in a different format. This documentation is also part of
the standard Python distribution.

(no courtesy copies by mail, please)

--
Dan Schmidt -> dfan@harmonixmusic.com, dfan@alum.mit.edu
Honest Bob & the http://www2.thecia.net/users/dfan/
Factory-to-Dealer Incentives -> http://www2.thecia.net/users/dfan/hbob/
Gamelan Galak Tika -> http://web.mit.edu/galak-tika/www/
Python to Perl Conversions [ In reply to ]
>Some have mentioned that I've left things out that are in
>more recent releases. I'm sorry, but I only have Mark Lutz's
>book to go on. There are no manpages for Python. Like most
>people, I'll wait until the next edition of the book is release
>rather than digging around elsewhere if the manpage are missing.

Coming from a strong UNIX and Perl background (probably not as strong
as you...), I *never* once used a Perl man page throughout
writing tens of thousands of lines of code. For that matter, I
never used the Tcl/Tk ones either. I've never considered man pages
to be the Single Right Way First Line of Documentation Offering When
Documenting a Language.

So, maybe you use man pages all the time with Perl. It is not
at all safe to assume that it's the primary means through which
people using Perl seek reference though (unless you've done some
sort of study I'm unaware of).

If you put me on any UNIX machine without man pages containing
descriptions and command-line usage of the tools there, I would
be royally pissed.

I don't know, your little jab there in an otherwise great reference
document posting seemed completely petty to me. It makes me think
you stuck it in there as a little "See, I'm dissing them like I am
supposed to!" due to the fact that you posted the message to both
c.l.perl and c.l.python.

Whatever... It just bugged me and really seems like that kind of
thing is the CAUSE of the Perl/Python geeky religious pettiness...in
a document showing how to move between both religious worlds no less!

OK, I am truly rambling now.
Python to Perl Conversions [ In reply to ]
jblaine@shell2.shore.net (Jeff Blaine) writes:

| I don't know, your little jab there in an otherwise great reference
| document posting seemed completely petty to me. It makes me think
| you stuck it in there as a little "See, I'm dissing them like I am
| supposed to!" due to the fact that you posted the message to both
| c.l.perl and c.l.python.

Actually, he left that paragraph out of the copy he posted to
comp.lang.perl.misc.

--
Dan Schmidt -> dfan@harmonixmusic.com, dfan@alum.mit.edu
Honest Bob & the http://www2.thecia.net/users/dfan/
Factory-to-Dealer Incentives -> http://www2.thecia.net/users/dfan/hbob/
Gamelan Galak Tika -> http://web.mit.edu/galak-tika/www/
Python to Perl Conversions [ In reply to ]
[courtesy cc of this posting mailed to cited author]

In comp.lang.python,
jblaine@shell2.shore.net (Jeff Blaine) writes:
:If you put me on any UNIX machine without man pages containing
:descriptions and command-line usage of the tools there, I would
:be royally pissed.

Exactly. And I thought my statements were rather subdued for
being royally pissed.

:I don't know, your little jab there in an otherwise great reference
:document posting seemed completely petty to me. It makes me think
:you stuck it in there as a little "See, I'm dissing them like I am
:supposed to!" due to the fact that you posted the message to both
:c.l.perl and c.l.python.

Don't be silly. That wasn't that at all. Online searchable documentation
is critical in a technical subject like this. Imagine libc without
manpages! Or having no manpages for the shell tools. Now, you might
now be aware of this, but I happened to *write* most of that on-line
documenation for Perl. I'm super senstitive to not being able to look
up docs using standard CLI text-based tools. As you said, you would be
frustrated not to have docs for tools or libraries.

Something the python community might should learn here from the perl
community is our zealous position on usable documentation. HTML alone
sucks, as does putting things only on the web (two different issues).
That I can't even get "man python" to come up pisses me off more than
you can imagine. I strongly feel that you really should consider making
something easy for CLI people to use just like any other tool or library.
That's why we have "pod" as base docs, which can convert into HTML,
text, info, latex, frame, troff (manpages), etc. It makes it easy to
run grep or find programs on. This is very important. And each module
automatically installs that module's manpage (and optionally html doc,
but this is less popular amongst perl folks). That gets it added to
the apropos and whatis and man commands automatically. This is about
0.002% of what the MakeMaker thingie in Perl does, but it's the part
that matters for docs. I've surely heard Python folks drooling over it
for a long time. Also, the CPAN autoinstaller than runs it all for you.
All very spiffy.

--tom
--
"It is inhumane, in my opinion, to force people who have a genuine
medical need for coffee to wait in line behind people who apparently
view it as some kind of recreational activity."
-- Dave Barry
Python to Perl Conversions [ In reply to ]
Tom Christiansen <tchrist@mox.perl.com> writes:

| Online searchable documentation is critical in a technical subject
| like this. Imagine libc without manpages! Or having no manpages
| for the shell tools. Now, you might now be aware of this, but I
| happened to *write* most of that on-line documenation for Perl. I'm
| super senstitive to not being able to look up docs using standard
| CLI text-based tools. As you said, you would be frustrated not to
| have docs for tools or libraries.

I use the documentation in info format, which is basically plaintext
and easily searchable with text-based tools. Select "GNU Info" from
<http://www.python.org/doc/current/download.html>.

I'm not trying to be an apologist for the lack of man pages, just
helping you find the plaintext documentation you (and I) prefer.

(no courtesy cc's, please)

--
Dan Schmidt -> dfan@harmonixmusic.com, dfan@alum.mit.edu
Honest Bob & the http://www2.thecia.net/users/dfan/
Factory-to-Dealer Incentives -> http://www2.thecia.net/users/dfan/hbob/
Gamelan Galak Tika -> http://web.mit.edu/galak-tika/www/
Python to Perl Conversions [ In reply to ]
>In comp.lang.python,
> jblaine@shell2.shore.net (Jeff Blaine) writes:
>:If you put me on any UNIX machine without man pages containing
>:descriptions and command-line usage of the tools there, I would
>:be royally pissed.
>
>Exactly. And I thought my statements were rather subdued for
>being royally pissed.

Heh. Alright...it's just that you and *at least* myself are coming from
very different views and usage expectations on this. Perl didn't always
have pod, and more to the point Perl did not have pod when I learned it.
Perl had a gigantic man page that was so cumbersome to use, I didn't.

I always used the HTML version that used to exist at ufl.edu and it didn't
bother me in the least. As a matter of fact, I found it much more useful
than any existing Perl documentation.

Because of that, I've never expected language reference to be available
in man page form on any UNIX box, with the exception of C function
reference which has just been there from day one for me. So, I honestly
never blinked an eye when Python's docs were in HTML format, especially
given its wide platform availability (specifically non-UNIX) from
early versions. I installed the documentation tarball, pointed lynx and
GUI browsers at it and that was that.

Even *when* Perl got pod, I didn't use the man pages due to their flat
and linear nature.

I know what version of Python I am running, and I know where the docs
for that version are. Using Python 1.5.x and expecting a book which
is several years old (and based on 1.4) to be your source of
day-to-day reference seems pretty silly if you ask me.

As a royally-pissed-if-expected-tool-man-pages-are-not-there kinda
person, it doesn't bother me at all if a 3rd party language gets installed
and does not have man pages for each function or functionality. I
can certainly agree that SOME sort of man page for 'python.1' would
make some sense, and more than that would only make more people happy...

Now, having said ALL of that, recently Transarc/IBM decided to STOP
doing man pages for AFS. Man pages that I knew existed and depended
on. This removal of service is the kind of thing that can really piss
a person off, and that seems to be what you're feeling coming from your
expectations. Tom Christiansen believes man pages should exist for
any runnable command on a UNIX box (and ideally more than just that)
(right?). Tom Christiansen does not find any for Python. Tom
Christiansen is pissed.

Anyway, I seem to be entirely unable to quickly and concisely make a
statement anymore :) I guess I more or less agree with you, I just
don't feel as strongly about it as you do for many reasons which are
spelled out in both of our messages.

>:I don't know, your little jab there in an otherwise great reference
>:document posting seemed completely petty to me. It makes me think
>:you stuck it in there as a little "See, I'm dissing them like I am
>:supposed to!" due to the fact that you posted the message to both
>:c.l.perl and c.l.python.
>
>Don't be silly. That wasn't that at all.

OK, sorry. I was really hoping that wasn't the case.

>That's why we have "pod" as base docs, which can convert into HTML,
>text, info, latex, frame, troff (manpages), etc. It makes it easy to
>run grep or find programs on. This is very important. And each module
>automatically installs that module's manpage (and optionally html doc,
>but this is less popular amongst perl folks). That gets it added to
>the apropos and whatis and man commands automatically. This is about
>0.002% of what the MakeMaker thingie in Perl does, but it's the part
>that matters for docs. I've surely heard Python folks drooling over it
>for a long time.

Indeed, something like pod would be great, and many Pythoners definitely
do agree.

And before someone suggests gendoc, I've tried to get 'gendoc' and whatever
it used to be called to simply install and function properly 3 separate
times now over the last 2 years and have given up after an hour of work
and editing source code each time.
Python to Perl Conversions [ In reply to ]
Quoth Tom Christiansen <tchrist@mox.perl.com>,
...
| Something the python community might should learn here from the perl
| community is our zealous position on usable documentation. HTML alone
| sucks, as does putting things only on the web (two different issues).
| That I can't even get "man python" to come up pisses me off more than
| you can imagine. I strongly feel that you really should consider making
| something easy for CLI people to use just like any other tool or library.
| That's why we have "pod" as base docs, which can convert into HTML,
| text, info, latex, frame, troff (manpages), etc. It makes it easy to
| run grep or find programs on. This is very important. And each module
| automatically installs that module's manpage (and optionally html doc,
| but this is less popular amongst perl folks). That gets it added to
| the apropos and whatis and man commands automatically. This is about
| 0.002% of what the MakeMaker thingie in Perl does, but it's the part
| that matters for docs. I've surely heard Python folks drooling over it
| for a long time. Also, the CPAN autoinstaller than runs it all for you.
| All very spiffy.

Searchable CLI documentation is a good thing, and I take that as the main
point of your post here, but the way Perl and Tcl dump man pages into man3
isn't something Python needs to emulate on my account. Man pages could
be disposed in the same name-space-sensitive way we design libraries,
modules, etc., and if anyone feels like working the Python documentation
into man pages I hope that will be considered.

It's no surprise to me that Python documentation doesn't appear as man
pages, anyway, it doesn't seem like a good match for the information
or the community. Among the alternatives I know of, I'd go with HTML.

Donn Cave, University Computing Services, University of Washington
donn@u.washington.edu
Python to Perl Conversions [ In reply to ]
In article <37bc2ee5@cs.colorado.edu>, Tom Christiansen
<tchrist@mox.perl.com> writes
...
It's a good thing I'm in the killfile as otherwise my response would be
raising the blood pressure of this arrogant person. Perl with any amount
of documentation sucks when compared to python. It's not so much the bad
language structure/syntax but the lack of sensible advice. Also (it's a
number thing) there are good reasons for maths/engineering types like
myself to prefer python.
>
>Don't be silly. That wasn't that at all. Online searchable documentation
>is critical in a technical subject like this. Imagine libc without
>manpages! Or having no manpages for the shell tools. Now, you might
>now be aware of this, but I happened to *write* most of that on-line
>documenation for Perl. I'm super senstitive to not being able to look
>up docs using standard CLI text-based tools. As you said, you would be
>frustrated not to have docs for tools or libraries.
>
>Something the python community might should learn here from the perl
>community is our zealous position on usable documentation. HTML alone
>sucks, as does putting things only on the web (two different issues).
>That I can't even get "man python" to come up pisses me off more than
>you can imagine. I strongly feel that you really should consider making
>something easy for CLI people to use just like any other tool or library.
>That's why we have "pod" as base docs, which can convert into HTML,
>text, info, latex, frame, troff (manpages), etc. It makes it easy to
>run grep or find programs on. This is very important. And each module
>automatically installs that module's manpage (and optionally html doc,
>but this is less popular amongst perl folks). That gets it added to
>the apropos and whatis and man commands automatically. This is about
>0.002% of what the MakeMaker thingie in Perl does, but it's the part
>that matters for docs. I've surely heard Python folks drooling over it
>for a long time. Also, the CPAN autoinstaller than runs it all for you.
>All very spiffy.
>
>--tom

--
Robin Becker
Python to Perl Conversions [ In reply to ]
Jeff Blaine writes:
> can certainly agree that SOME sort of man page for 'python.1' would
> make some sense, and more than that would only make more people happy...

'man python' works for me; it's installed by default. You can use
all the usual manpage handling tools with it, too, including troff &
apropos.


-Fred

--
Fred L. Drake, Jr. <fdrake@acm.org>
Corporation for National Research Initiatives
Python to Perl Conversions [ In reply to ]
Quoth jblaine@shell2.shore.net (Jeff Blaine),
...
| I know what version of Python I am running, and I know where the docs
| for that version are. Using Python 1.5.x and expecting a book which
| is several years old (and based on 1.4) to be your source of
| day-to-day reference seems pretty silly if you ask me.

Worth pointing out it wouldn't be a showstopper, though. There would
be some rough spots (changes in exception handling come to mind), but
overall I think the PostScript (library, reference, tutorial) doc from
1.1 would be pretty much on target (happens to be the first version I
remember. This core stability is itself a virtue of Python, but I wonder
if it has inhibited the development of the documentation.) Now if you
wanted to produce a comprehensive article on the features missing from
Python, you certainly would be missing a bet not to refer to current
documentation, but that's an unusual objective.

Donn Cave, University Computing Services, University of Washington
donn@u.washington.edu
Python to Perl Conversions [ In reply to ]
Donn> This core stability is itself a virtue of Python, but I wonder if
Donn> it has inhibited the development of the documentation.

It's probably reduced the number of gratuitous Python books and
updates... ;-)

Skip Montanaro | http://www.mojam.com/
skip@mojam.com | http://www.musi-cal.com/~skip/
847-971-7098
Python to Perl Conversions [ In reply to ]
In article <37bc505b@cs.colorado.edu>, Tom Christiansen
<tchrist@mox.perl.com> writes
>
...
>
>I never killfiled you. Why are you trying to start a flame war? And why
>did you respond with a stupid Jeopardy style Answer before the Question,
>without even trimming? Is your newsreader broken, or haven't you ever
>bothered to read news.announce.newusers to learn how to use Usenet?
>
>Followups to /dev/null.
>
>--tom
too easy
--
Robin Becker
Python to Perl Conversions [ In reply to ]
In article <37bc487e@cs.colorado.edu>,
Tom Christiansen <tchrist@mox.perl.com> wrote:
>
>The Prisoners of Bill gets HTML, regular Unix users get manpages,
>and anyone can have simple text. And everyone is happy.

Excuse me, but I do much of my Python development on Linux and Solaris,
where Lynx (with its ease of navigation) does a much better job on
documentation than man pages -- for me. (I mentioned this in another
post, but I figured sticking in the OS references was worth a repeat.)
I can't tell you how many times I've gotten pissed at having one Perl
man page reference another with no direct mechanism for getting there.
--
--- Aahz (@netcom.com)

Androgynous poly kinky vanilla queer het <*> http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6 (if you want to know, do some research)
Python to Perl Conversions [ In reply to ]
[courtesy cc of this posting mailed to cited author]

In comp.lang.python,
Donn Cave <donn@u.washington.edu> writes:
:Searchable CLI documentation is a good thing, and I take that as the main
:point of your post here, but the way Perl and Tcl dump man pages into man3
:isn't something Python needs to emulate on my account.

I agree entirely, and Perl shouldn't be doing that. It uses
it's only manpath, which is separate. For example:

% perl -V:man.dir
man1dir='/usr/local/perl/man/man1'
man3dir='/usr/local/perl/man/man3'

That tells me that I can just use as an alias pman to be
"man -P /usr/local/perl/man" or "MANPATH=/usr/local/perl/man man"

Your site may have them installed in different locations, but
the principle is the same.

But this doesn't help the module documentation issue. When a
new module is installed, I get to see it with apropos (that's
"man -k" for some of you):

% pman -k net
perlfaq9 (1) - Networking ($Revision: 1.24 $, f(CW$Date: 1999/01/08 05:39:48 $)
lwp-download (1) - fetch large files from the net
CGI::Cookie (3pm) - Interface to Netscape Cookies
IO::Socket::INET (3pm) - Object interface for AF_INET domain sockets
Mail::Internet (3pm) - manipulate Internet format (RFC 822) mail messages
Net::Cmd (3pm) - Network Command class (as used by FTP, SMTP etc)
Net::Domain (3pm) - Attempt to evaluate the current host's internet name and domain
Net::DummyInetd (3pm) - A dummy Inetd server
Net::FTP (3pm) - FTP Client class
Net::NNTP (3pm) - NNTP Client class
Net::Netrc (3pm) - OO interface to users netrc file
Net::PH (3pm) - CCSO Nameserver Client class
Net::POP3 (3pm) - Post Office Protocol 3 Client class (RFC1081)
Net::Ping (3pm) - check a remote host for reachability
Net::SMTP (3pm) - Simple Mail Transfer Protocol Client
Net::SNPP (3pm) - Simple Network Pager Protocol Client
Net::Telnet (3pm) - interact with TELNET port or other TCP ports
Net::Time (3pm) - time and daytime network client interface
Net::hostent (3pm) - by-name interface to Perl's built-in gethost*() functions
Net::netent (3pm) - by-name interface to Perl's built-in getnet*() functions
Net::protoent (3pm) - by-name interface to Perl's built-in getproto*() functions
Net::servent (3pm) - by-name interface to Perl's built-in getserv*() functions
Socket, sockaddr_in, sockaddr_un, inet_aton, inet_ntoa (3pm) - load the C socket.h defines and structure manipulators

Nifty, eh? I wonder how to do that when you install modules in Python?
How close an automated, MakeMaker-like thing do you have?

:Man pages could be disposed in the same name-space-sensitive way we
:design libraries, modules, etc., and if anyone feels like working the
:Python documentation into man pages I hope that will be considered.

I'm still dumb-founded that so many Python people don't use the manpages,
or evens expects them! Considering how much I've complained, I'd
certainly be willing to give it a try. Do they come in a basic format
that can just be passed through a filter? And no, we don't really use
manpages for Perl. We use pod, then translate to many formats.
The Prisoners of Bill gets HTML, regular Unix users get manpages,
and anyone can have simple text. And everyone is happy.

--tom
--
If you choose not to decide, you still have made a choice. --Rush
Python to Perl Conversions [ In reply to ]
I wrote:
:I agree entirely, and Perl shouldn't be doing that. It uses
:it's only manpath, which is separate. For example:

I surely meant

its own manpath

not

it's only manpath

--tom
--
#define SVs_RMG 0x00008000 /* has random magical methods */
--Larry Wall, from sv.h in the v5.0 perl distribution
Python to Perl Conversions [ In reply to ]
In article <7phk5v$ot1@dfw-ixnews8.ix.netcom.com>,
Aahz Maruch <aahz@netcom.com> wrote:
>I can't tell you how many times I've gotten pissed at having one Perl
>man page reference another with no direct mechanism for getting there.

I bet it doesn't outnumber the times I've gotten pissed at lynx for not
having a regexp search.

--
Alan "If it doesn't go through my $PAGER, it's not documentation" Curry
Python to Perl Conversions [ In reply to ]
[courtesy cc of this posting mailed to cited author]

In comp.lang.python,
Robin Becker <robin@jessikat.demon.co.uk> writes:
:It's a good thing I'm in the killfile as otherwise my response would be
:raising the blood pressure of this arrogant person. Perl with any amount
:of documentation sucks when compared to python. It's not so much the bad
:language structure/syntax but the lack of sensible advice. Also (it's a
:number thing) there are good reasons for maths/engineering types like
:myself to prefer python.

I never killfiled you. Why are you trying to start a flame war? And why
did you respond with a stupid Jeopardy style Answer before the Question,
without even trimming? Is your newsreader broken, or haven't you ever
bothered to read news.announce.newusers to learn how to use Usenet?

Followups to /dev/null.

--tom
--
The very fact that it's possible to write messy programs in Perl is also
what makes it possible to write programs that are cleaner in Perl than
they could ever be in a language that attempts to enforce cleanliness.
--Larry Wall
Python to Perl Conversions [ In reply to ]
Tom Christiansen <tchrist@mox.perl.com> wrote:
> Per your collective requests, here is one of the documents
> with my collective observations from learning Python.

Hm, there seems to be only a discussion on whether docs should be in man
pages or not in response to this posting here.

I thought the posting was neat. It wasn't particularly useful to me,
but it's neat. It must've taken quite a lot of work. Thanks!

Regards,

Martijn
Python to Perl Conversions [ In reply to ]
[courtesy cc of this posting mailed to cited author]

In comp.lang.python,
m.faassen@vet.uu.nl (Martijn Faassen) writes:
:Hm, there seems to be only a discussion on whether docs should be in man
:pages or not in response to this posting here.

Yes, that has been disappointing.

:I thought the posting was neat. It wasn't particularly useful to me,
:but it's neat. It must've taken quite a lot of work. Thanks!

I'm very glad you liked it. Thank you.

--tom
--
Weinberg's Second Law: If builders built buildings the way programmers
write programs, the first woodpecker to come along would destroy civilization.
Python to Perl Conversions [ In reply to ]
Tom Christiansen wrote:

> This article was posted to the Perl newsgroup, but I have duplicated
> the posting here without crossposting to avoid flame wars.

Thanks for this posting. Since I'm a pragmatic programmer, I'd like
any information possible. Such infos translate to money, while it
is more difficult to convert the other type of postings
here into some visible added value.

We could use the same energie which goes into flaming for
creating new design patterns or sophisticated applications or
whatever makes life interesting. All the scripting languages
have long todo lists (, not tupples).

Once they prohibited me to use more than one language for
a project; I had to stay with perl and even without OO.
The more languages, the better for fighting alzheimer:-)

Cheers, Per.
--
Per Kistler kistler@fnmail.com / kistler@gmx.net
------------------------------------------------------------
Python to Perl Conversions [ In reply to ]
On 19 Aug 1999 08:21:55 -0700, Tom Christiansen wrote:
>Per your collective requests, here is one of the documents
>with my collective observations from learning Python.

A very cool document. Looks like my observations about Perl, except I
didn't write anything down (too stupid-lazy).

>This article was posted to the Perl newsgroup, but I have duplicated
>the posting here without crossposting to avoid flame wars.

Good idea. Pity it didn't work, eh? ;-)

>--tom

>x / y Same for floats, but Perl doesn't do
> integer division here usually. Python
> things 3/4 is 0 (and false), but 3.0/4.0 is 0.75

Q: can Perl be made to do integer division here if you declare both
variables as integer? I seem to recall something like that (but it's been
a while).

> strings aren't numbers, nor are they
> autoconverted.

This is important to Python. And Perl, of course.

>float(x) not applicable

Except for variables declared integer, right?

>pow(x,y) x ** y

x**y is also valid Python syntax.

>x << n, x >> n same, although Perl works differently if
> you go over 31 bits: Python keeps giving
> you 0, whereas Perl wraps. 1<<34 is 0 in
> python but 4 in perl.

Facinating. Is the Perl << actually a rotate, or is that a special case
for n > 31?

>~x same-ish, but see |&^ above for details.
> In particular, you can't negate bitstrings
> in python.

I'm not sure what bitstrings are, but Python's longs can certainly be
negated, and I'm not sure what more you can ask for without asking for
Common Lisp.

(Here's an idea: take Common Lisp, rename its functions, write a new
reader macro, and call it "Python 2.0"!)

>Python Construct Perl Equivalent
>===========================================================================

> Note that Python doesn't support hash
> slices, which in Perl are simple:
> @hash{k1,k2,k3} = (v1, v2, v3)

That's a good point, although I'm not sure what Python can do about it --
our slice semantics talk about gaps, and hashes don't have gaps. I
suspect we'd have to call it something other than slicing (this seems
pretty reasonable).

>hash(x) huh? "returns the hash value of the object,
> if any"

The key which a hash table would use to store and look up the indicated
data.

>hex(n) sprintf("%#x", n)
> Perl's hex() function is the opposite.
> It converts 22 into 37. Python's hex
> function converts 37 into 0x22. Oh my!

Now this is a cool difference, because it highlights a difference between
the languages. hex in Python converts from an integral number to a
string; in Perl it converts from a number which is treated as a string to
a number (which can be treated as a string).

Amusingly, applying hex repeatedly in Perl results in an ever-increasing
number.

I think Perl is more than a little oddball here. I tried to model what
was hapenning, but I couldn't figure it out. Ah, here we go, Perl does
the equivalent of converting the number into a string using radix 10, and
then reading that string into an integer using radix 16.

This is exactly what you'd want if you'd just read a hex number in which
didn't begin with "0x", so the read system misinterpreted it as a decimal.

Am I right? I'm pretty puzzled here...

>reload(module) First delete from %INC, then require the
> module again, as in:
> delete $INC{"Module.pm"}
> require Module;
> Note that Python doesn't directly support
> nested modules as in
> require Dir1::Dir2::Dir3::Module;
> except via a disgustingly named hackaround
> module.

True for 1.4, not true after that.

And "ni!" isn't disgusting -- what's disgusting is what the times have
come to, that ruffians can walk about saying "ni!" to innocent old ladies.

>str(x) I thought this was the same as repr().

Similar, identical in many cases. str() is more verbose (prettier) in
some cases.

>tuple(seq) n/a. This is a nasty hack to deal with the
> fact that (1,2,3) is different from [1,2,3].
> Hm... maybe it's like this:
> $aref = [1,2,3];
> @list = @$aref;

By "nasty hack" you mean "obvious consequence", of course. Just like
$obj->{$name} is an obvious consequence of interpolation.

Sorry, I'm getting editorial -- but then you tend to be very much so.

>file.flush() Either FH->autoflush(1) if you're using the
> aliasing modules, or else the klunky but
> fast:
> $old_fh = select(FH);
> $| = 1;
> select($old_fh);
> Note that this just sets autoflushing
> on each subsequent output on that handle.

Q: the Python version merely flushes the file, while the Perl version
looks like it's actually setting a permanent flag in the file to flush
frequently. Is that correct?

Python, OTOH, doesn't seem to have a way to set a file's flushing
properties -- you have to explicitly flush whenever you need it. True?

>sys.exit(status) exit(status) and no import is bloody
> necessary just to leave the program.
> But that Python does this by raising
> a SystemExit exception. Perl can use
> END{} handlers to catch these and do
> at-exit processing, and Python doesn't.
> You have to roll your own.

Python uses "finally:" and "except SystemExit:" blocks to do that. Is
that what you mean?

I seem to recall END blocks in Perl, although I never used them... Don't
they remain active forever, like C's atexit function? How do you
deactivate them?

>_exit(n) POSIX::_exit(n)

In Python _exit skips the atexit stuff. True in Perl?

--
-William "Billy" Tanksley
Python to Perl Conversions [ In reply to ]
[courtesy cc of this posting mailed to cited author]

On 19 Aug, Tom Christiansen wrote:
> In comp.lang.python,
> m.faassen@vet.uu.nl (Martijn Faassen) writes:
> :Hm, there seems to be only a discussion on whether docs should be in man
> :pages or not in response to this posting here.
>
> Yes, that has been disappointing.

I also appreciated your mapping between the two languages. How hard
would it be to write a reverse mapping? I know very little perl, but
occasionally need to look at an existing perl script and try to figure
out what it does. A table that gives the python equivalent of common
perl expressions could be very useful.

--
Greg McFarlane: INMS Telstra Australia (gregm@iname.com)
Today's forecast: Sunny, with occasional cloudy periods and a chance
of precipitation in some areas.
Python to Perl Conversions [ In reply to ]
This is a multi-part message in MIME format.
--------------9E2A9E0690D3CB0B20D4E039
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit

Tom Christiansen wrote:
> There are no manpages for Python.

I hate HTML documentation. I want printed documentation or I get seriously
pissed too. Fortunately Python has a nice set of printable documents in a
variety of formats and paper sizes. See:

http://www.python.org/doc/current/download.html

You are fundamentally incorrect in stating that there is no man page for
Python. There is a man page for Python in my /usr/local/man/man1 directory
on my Linux box. It does not cover the language syntax or the huge library
reference, but then neither does the man page for c++ cover its syntax or
the STL. For your benefit I've included the Python man page as an
attachment. I hope this helps clear up any misunderstanding you may have
about Python documentation.
--------------9E2A9E0690D3CB0B20D4E039
Content-Type: text/plain; charset=us-ascii; name="python.1"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline; filename="python.1"

.TH PYTHON "7 September, 1997"
.SH NAME
python \- an interpreted, interactive, object-oriented programming language
.SH SYNOPSIS
.B python
[
.B \-d
]
[
.B \-i
]
[
.B \-O
]
[
.B \-S
]
[
.B \-u
]
[
.B \-v
]
[
.B \-X
]
.br
[
.B \-c
.I command
|
.I script
|
\-
]
[
.I arguments
]
.SH DESCRIPTION
Python is an interpreted, interactive, object-oriented programming
language that combines remarkable power with very clear syntax.
For an introduction to programming in Python you are referred to the
Python Tutorial.
The Python Library Reference documents built-in and standard types,
constants, functions and modules.
Finally, the Python Reference Manual describes the syntax and
semantics of the core language in (perhaps too) much detail.
.PP
Python's basic power can be extended with your own modules written in
C or C++.
On most systems such modules may be dynamically loaded.
Python is also adaptable as an extension language for existing
applications.
See the internal documentation for hints.
.SH COMMAND LINE OPTIONS
.TP
.B \-d
Turn on parser debugging output (for wizards only, depending on
compilation options).
.TP
.B \-i
When a script is passed as first argument or the \fB\-c\fP option is
used, enter interactive mode after executing the script or the
command. It does not read the $PYTHONSTARTUP file. This can be
useful to inspect global variables or a stack trace when a script
raises an exception.
.TP
.B \-O
Turn on basic optimizations. This changes the filename extension for
compiled (bytecode) files from
.I .pyc
to
.I pyo.
.TP
.B \-S
Disable the import of the module
.I site
and the site-dependent manipulations of
.I sys.path
that it entails.
.TP
.B \-u
Force stdin, stdout and stderr to be totally unbuffered.
.TP
.B \-v
Print a message each time a module is initialized, showing the place
(filename or built-in module) from which it is loaded.
.TP
.B \-X
Make the standard exceptions strings instead of classes.
Use for backward compatibility with old code only.
.TP
.BI "\-c " command
Specify the command to execute (see next section).
This terminates the option list (following options are passed as
arguments to the command).
.SH INTERPRETER INTERFACE
The interpreter interface resembles that of the UNIX shell: when
called with standard input connected to a tty device, it prompts for
commands and executes them until an EOF is read; when called with a
file name argument or with a file as standard input, it reads and
executes a
.I script
from that file;
when called with
.B \-c
.I command,
it executes the Python statement(s) given as
.I command.
Here
.I command
may contain multiple statements separated by newlines.
Leading whitespace is significant in Python statements!
In non-interactive mode, the entire input is parsed befored it is
executed.
.PP
If available, the script name and additional arguments thereafter are
passed to the script in the Python variable
.I sys.argv ,
which is a list of strings (you must first
.I import sys
to be able to access it).
If no script name is given,
.I sys.argv
is empty; if
.B \-c
is used,
.I sys.argv[0]
contains the string
.I '-c'.
Note that options interpreted by the Python interpreter itself
are not placed in
.I sys.argv.
.PP
In interactive mode, the primary prompt is `>>>'; the second prompt
(which appears when a command is not complete) is `...'.
The prompts can be changed by assignment to
.I sys.ps1
or
.I sys.ps2.
The interpreter quits when it reads an EOF at a prompt.
When an unhandled exception occurs, a stack trace is printed and
control returns to the primary prompt; in non-interactive mode, the
interpreter exits after printing the stack trace.
The interrupt signal raises the
.I Keyboard\%Interrupt
exception; other UNIX signals are not caught (except that SIGPIPE is
sometimes ignored, in favor of the
.I IOError
exception). Error messages are written to stderr.
.SH FILES AND DIRECTORIES
These are subject to difference depending on local installation
conventions:
.IP /usr/local/bin/python
Recommended location of the interpreter.
.IP /usr/local/lib/python<version>
Recommended location of the directory containing the standard modules.
.SH ENVIRONMENT VARIABLES
.IP PYTHONHOME
Change the location of the standard Python libraries. By default, the
libraries are searched in <prefix>/lib/python<version> and
<exec_prefix>/lib/python<version>, where <prefix> and <exec_prefix>
are installation-dependent directories, both defaulting to
/usr/local. When $PYTHONHOME is set to a single directory, its value
replaces both <prefix> and <exec_prefix>. To specify different values
for these, set $PYTHONHOME to <prefix>:<exec_prefix>.
.IP PYTHONPATH
Augments the default search path for module files.
The format is the same as the shell's $PATH: one or more directory
pathnames separated by colons.
Non-existant directories are silently ignored.
The default search path is installation dependent, but generally
begins with <prefix>/lib/python<version> (see PYTHONHOME below).
The default search path is always appended to $PYTHONPATH.
If a script argument is given, the directory containing the script is
inserted in the path in front of $PYTHONPATH.
The search path can be manipulated from within a Python program as the
variable
.I sys.path .
.IP PYTHONSTARTUP
If this is the name of a readable file, the Python commands in that
file are executed before the first prompt is displayed in interactive
mode.
The file is executed in the same name space where interactive commands
are executed so that objects defined or imported in it can be used
without qualification in the interactive session.
You can also change the prompts
.I sys.ps1
and
.I sys.ps2
in this file.
.IP PYTHONDEBUG
If this is set to a non-empty string it is equivalent to specifying
the \fB\-d\fP option.
.IP PYTHONINSPECT
If this is set to a non-empty string it is equivalent to specifying
the \fB\-i\fP option.
.IP PYTHONUNBUFFERED
If this is set to a non-empty string it is equivalent to specifying
the \fB\-u\fP option.
.IP PYTHONVERBOSE
If this is set to a non-empty string it is equivalent to specifying
the \fB\-v\fP option.
.SH SEE ALSO
Python Tutorial
.br
Python Library Reference
.br
Python Reference Manual
.SH AUTHOR
.nf
Guido van Rossum
CNRI
1895 Preston White Drive
Reston, VA 20191
USA
.PP
E-mail: guido@cnri.reston.va.us, guido@python.org
.fi
.PP
And a cast of thousands.
.SH INTERNET RESOURCES
Web site: http://www.python.org
.br
FTP site: ftp://ftp.python.org
.br
Newsgroup: comp.lang.python
.SH COPYRIGHT
Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
The Netherlands.
.IP " "
All Rights Reserved
.PP
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the names of Stichting Mathematisch
Centrum or CWI or Corporation for National Research Initiatives or
CNRI not be used in advertising or publicity pertaining to
distribution of the software without specific, written prior
permission.

While CWI is the initial source for this software, a modified version
is made available by the Corporation for National Research Initiatives
(CNRI) at the Internet address ftp://ftp.python.org.

STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.

--------------9E2A9E0690D3CB0B20D4E039--
Python to Perl Conversions [ In reply to ]
I'll skip parts that have already been addressed (hopefully).

On 19 Aug 1999 08:21:55 -0700, Tom Christiansen <tchrist@mox.perl.com>
wrote:
>Per your collective requests, here is one of the documents
>with my collective observations from learning Python.

Cool.

[snips left unmarked]

>delattr(object,name) n/a? "delete named attribute from object".
> I suppose this might be
> delete $obj->{name}
> but that's pretty uncool to do it without
> asking the object.

BTW, Python does ask the object. If object is of a builtin type, this
delattr (or "del object.attr" where "attr" is name's value) will call
the C function that the type defines for __delattr__. If object is an
instance of a class that has a __delattr__ method, then delattr will
be equivalent to object.__delattr__(name). If object's class doesn't
define __delattr__, then Python will simply delete that attribute.

>eval(code) Same as Perl, but Perl's handles
> statements, and python's only handles
> expressions. Also, python hurls an
> exception if it doesn't like you,
> whereas Perl sets $@. People use this
> to convert string to numbers. This is
> a terrible security hazard.

Not used so much for converting strings to numbers since int(x),
float(x), and long(x) were changed to handle strings. This change
(IIRC) was made from 1.4 -> 1.5, I believe, to solve this very issue.

>exec(code) eval(code); plus see previous entry.

I only say this in case you revise this document for use elsewhere:
The parens are unnecessary. "exec" is a statement keyword.

>getattr(obj,name) n/a? maybe just $obj->{$name}. I don't
> understand why this exits. Oh heck, yes I
> do. Because you can say
> name = "widget_count"
> obj.name
> Because there's no interpolation and
> otherwise it will look up name. Oh my.
> This is like the apply() mess.

It's really not so bad. This actually keeps Python simple and clear.
IMO, it is not desirable for interpolation to exist for the usual
attribute access method "obj.name". In debugging a complicated class
definition, this unambiguity can be very important.

We could add special punctuation to do this interpolation (which, if I
read you correctly, perl does?), but getattr works just as well
without futzing with the grammar.

Truly, getattr isn't used a whole lot. I don't think that we'd
benefit from interpolation.

>hash(x) huh? "returns the hash value of the object,
> if any"

Most (all?) immutable objects and class instances that define a
__hash__ method can be assigned a hash value with this function. This
value is the same one that is used internally for dictionaries (IIRC).
This can be useful for some arcane things.

>input(prompt?) n/a. This reads and evals the input
> stream! Needed because otherwise you can't
> read a number. Or you could read the
> string and convert it. Ick. Security
> hazard waiting to happen.

The number issue changed from 1.4 to 1.5, so no-one uses input to take
care of numbers anymore. The only thing I think it would really be
used for anymore is a quick-and-dirty interpreter shell.

>reload(module) First delete from %INC, then require the
> module again, as in:
> delete $INC{"Module.pm"}
> require Module;
> Note that Python doesn't directly support
> nested modules as in
> require Dir1::Dir2::Dir3::Module;
> except via a disgustingly named hackaround
> module.

Again (whoops, there goes my promise), this changed from 1.4 to 1.5.
You owe us a shrubbery.

>setattr(obj,name,value) $obj->{$name} = $value;
> Interpolation wins again. See getattr.

Shrug. Simplicity won in Guido's mind, I guess.

>str(x) I thought this was the same as repr().

repr() *should* return a string that can be popped into eval and
recover the original object (well, one that is equivalent in value to
the original). str() is sometimes used for a prettier version
designed for viewing, not evaluating.

E.g. for Numeric Python arrays
>>> from Numeric import *
>>> a = reshape(arange(16), (4,4))
>>> print repr(a)
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
>>> print str(a)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]

>tuple(seq) n/a. This is a nasty hack to deal with the
> fact that (1,2,3) is different from [1,2,3].
> Hm... maybe it's like this:
> $aref = [1,2,3];
> @list = @$aref;

Not so nasty. Tuples have properties (like immutability and
hashability) that justify their co-existence with lists. A function
to convert objects to tuples is desirable, just like int(), float(),
list(), etc. are desirable.

>sys.exit(status) exit(status) and no import is bloody
> necessary just to leave the program.
> But that Python does this by raising
> a SystemExit exception. Perl can use
> END{} handlers to catch these and do
> at-exit processing, and Python doesn't.
> You have to roll your own.

Non-issue really. There aren't many times where sys.exit() is needed.
If the interpreter is run in non-interactive mode, it will exit when
the script is completed successfully or it hits an unhandled
exception. Exiting the interpeter from interactive mode is done by
the user with Ctrl-D on UNIX and CTRL-Z on Windows.

Unless you really need to set the exit status, explicitly calling
sys.exit or raising SystemExit isn't usually beneficial. The default
behaviour is sufficient for most contexts, especially debugging in
interactive mode. Instead of exiting when it hits an unhandled
exception in interactive mode, the interpreter gives you the prompt.
From there, you can sometimes diagnose the problem.

>sys.exitfunc This is one function to call on normal exit
> (not exception exits, unlike perl).
> It would have to manage all the handlers
> in your roll-your-own scheme. Very ugly.

Not much of an issue, really.

> +-------------------------------------------------------------+
> | POSIX library. These aren't there unless you have imported |
> | the library module via "import posix". |
> +-------------------------------------------------------------+

Generally, you should use the os module which loads the right
OS-dependent module for your environment.

Thanks for listening.

>--
>If you consistently take an antagonistic approach, however, people are
>going to start thinking you're from New York. :-)
> --Larry Wall to Dan Bernstein in <10187@jpl-devvax.JPL.NASA.GOV>

Robert Kern |
----------------------|"In the fields of Hell where the grass grows high
This space | Are the graves of dreams allowed to die."
intentionally | - Richard Harter
left blank. |

1 2  View All