Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Newbie Questions: Swithing from Perl to Python

Reply
Thread Tools

Newbie Questions: Swithing from Perl to Python

 
 
Luther Barnum
Guest
Posts: n/a
 
      10-26-2003
I am a new Python programmer and I am having a few difficulties. I love Perl
and I am just trying to learn Python because it is used heavily at work. It
looks pretty cool so I am diving in. I'm sure they are easy but I not sure
how to proceed.

1. How can I run a program and modify the output on the fly then send it to
standard output.

Example in Perl:

ex. open(LS_PIPE, "/usr/bin/ls |");
while(<LS_PIPE>) {
s/this/that/g;
print;
}
close(LS_PIPE);


2. How can I sort and print out a hash.

Example in Perl:

ex. foreach $string (sort keys %hash) {
print("$string = $hash{$string}\n");
}

In Perl these are very easy tasks, but I am finding it a little difficult to
understand.


 
Reply With Quote
 
 
 
 
Hans Nowak
Guest
Posts: n/a
 
      10-26-2003
Luther Barnum wrote:
> I am a new Python programmer and I am having a few difficulties. I love Perl
> and I am just trying to learn Python because it is used heavily at work. It
> looks pretty cool so I am diving in. I'm sure they are easy but I not sure
> how to proceed.
>
> 1. How can I run a program and modify the output on the fly then send it to
> standard output.
>
> Example in Perl:
>
> ex. open(LS_PIPE, "/usr/bin/ls |");
> while(<LS_PIPE>) {
> s/this/that/g;
> print;
> }
> close(LS_PIPE);


I don't know enough Perl to be certain, but maybe it's something like:

p = os.popen("/usr/bin/ls")
for line in p.readlines():
line = line.replace("this", "that")
print line
p.close()

> 2. How can I sort and print out a hash.
>
> Example in Perl:
>
> ex. foreach $string (sort keys %hash) {
> print("$string = $hash{$string}\n");
> }


# assuming we have a dict called d
items = d.items() # get all (key, value) pairs from the dict
items.sort() # sort them
for key, value in items:
print "%s = %s" % (key, value)

HTH,

--
Hans ((E-Mail Removed))
http://zephyrfalcon.org/



 
Reply With Quote
 
 
 
 
Todd Stephens
Guest
Posts: n/a
 
      10-26-2003
On Sat, 25 Oct 2003 21:34:23 -0400, Luther Barnum wrote:

> 2. How can I sort and print out a hash.
>
> Example in Perl:
>
> ex. foreach $string (sort keys %hash) {
> print("$string = $hash{$string}\n");
> }
> }


Well, as a Python learner myself, I am going to attempt this for my own
education as well. I think you are looking for a dictionary in Python.
Let's say you have a dictionary 'dict' that contains something like this:

>>> dict = {'a':'me', 'b':'myself', 'c':'I'}


To print the dictionary as you iterate over it is simple:

>>> for key in dict:

.... print key, '=', dict[key]

This gives me:

a = me
c = I
b = myself

The order it prints could vary each time. I am not sure how to print a
sorted list from a dictionary. I think this would probably involve
assigning the dictionary elements to a list, then printing the sorted
list(s). I would like to see the code for that myself. BTW, Go Bucs.

--
Todd Stephens
 
Reply With Quote
 
Roy Smith
Guest
Posts: n/a
 
      10-26-2003
In article <jEEmb.37394$(E-Mail Removed)>,
"Luther Barnum" <(E-Mail Removed)> wrote:

> I am a new Python programmer and I am having a few difficulties. I love Perl
> and I am just trying to learn Python because it is used heavily at work. It
> looks pretty cool so I am diving in. I'm sure they are easy but I not sure
> how to proceed.


Check out the library reference at

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

> 1. How can I run a program and modify the output on the fly then send it to
> standard output.
>
> Example in Perl:
>
> ex. open(LS_PIPE, "/usr/bin/ls |");
> while(<LS_PIPE>) {
> s/this/that/g;
> print;
> }
> close(LS_PIPE);


Take a look at the popen2 module for the pipe functionality. The "while
(<LS_PIPE>)" is handled by readlines(), or just iterating over a file
(read the reference manual and/or tutorial on file objects). The re
module gets you perl-like regular expressions.

On the other hand, the dircache and os.path modules provides simplier
ways to iterate over a list of filenames in a directory.

> 2. How can I sort and print out a hash.
>
> Example in Perl:
>
> ex. foreach $string (sort keys %hash) {
> print("$string = $hash{$string}\n");
> }
>
> In Perl these are very easy tasks, but I am finding it a little difficult to
> understand.


The Python version of a hash is called a dictionary. For the above, you
want to do something along the lines of:

keys = myDict.keys()
keys.sort()
for key in keys:
print "%s = %s" % (key, myDict[key])

If you come from a Perl background, it may take a while to get used to
the Pythonic way of doing things, but it'll start to make sense quickly.
 
Reply With Quote
 
Luther Barnum
Guest
Posts: n/a
 
      10-26-2003
I see your from the Tampa area also, cool. That part seems pretty easy but
what I'm looking for is incrementing a counter. I use this all the time for
summarizing log files. I would probably prefer to keep using Perl but I work
in a place where Python is used much more than Perl so I want to learn it
the Python way.

Here is another example:

ex:

While(<FILE>) {
chomp;
if(/(\w+ # Date
\s+ # Space
\d+ # Day
\s+ # Space
(\w+) # Server
\s+ # Space
(\w+)/x) { # Error

$server = $1;
$error = $2;

$server_totals{$server}++;
$error_totals{$error}++;
}
}

With this code, I now have a hash that will total each type of error and
server. If I can concur this in Python, I will be extremely happy. I can
learn the rest over time but this is something that I use constantly as I
am a Unix Administrator.

Luther


"Todd Stephens" <(E-Mail Removed)> wrote in message
newsan.2003.10.26.01.52.23.855415.55687@tampabay .rr.com...
> On Sat, 25 Oct 2003 21:34:23 -0400, Luther Barnum wrote:
>
> > 2. How can I sort and print out a hash.
> >
> > Example in Perl:
> >
> > ex. foreach $string (sort keys %hash) {
> > print("$string = $hash{$string}\n");
> > }
> > }

>
> Well, as a Python learner myself, I am going to attempt this for my own
> education as well. I think you are looking for a dictionary in Python.
> Let's say you have a dictionary 'dict' that contains something like this:
>
> >>> dict = {'a':'me', 'b':'myself', 'c':'I'}

>
> To print the dictionary as you iterate over it is simple:
>
> >>> for key in dict:

> ... print key, '=', dict[key]
>
> This gives me:
>
> a = me
> c = I
> b = myself
>
> The order it prints could vary each time. I am not sure how to print a
> sorted list from a dictionary. I think this would probably involve
> assigning the dictionary elements to a list, then printing the sorted
> list(s). I would like to see the code for that myself. BTW, Go Bucs.
>
> --
> Todd Stephens
>



 
Reply With Quote
 
Roy Smith
Guest
Posts: n/a
 
      10-26-2003
Todd Stephens <(E-Mail Removed)> wrote:
> I am not sure how to print a sorted list from a dictionary. I think this would probably involve
> assigning the dictionary elements to a list, then printing the sorted
> list(s).


Exactly.

keys = myDict.keys()
keys.sort()
for key in keys:
print key

My personal opinion is that you should be able to do the simplier:

for key in myDict.keys().sort()
print key

but unfortunately, sort doesn't work like that. It sorts the list
in-place and does NOT return the sorted list.
 
Reply With Quote
 
Luther Barnum
Guest
Posts: n/a
 
      10-26-2003
That was great Hans, thanks. I gave another example that explains number two
a little better in another post.

Luther


"Hans Nowak" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> Luther Barnum wrote:
> > I am a new Python programmer and I am having a few difficulties. I love

Perl
> > and I am just trying to learn Python because it is used heavily at work.

It
> > looks pretty cool so I am diving in. I'm sure they are easy but I not

sure
> > how to proceed.
> >
> > 1. How can I run a program and modify the output on the fly then send it

to
> > standard output.
> >
> > Example in Perl:
> >
> > ex. open(LS_PIPE, "/usr/bin/ls |");
> > while(<LS_PIPE>) {
> > s/this/that/g;
> > print;
> > }
> > close(LS_PIPE);

>
> I don't know enough Perl to be certain, but maybe it's something like:
>
> p = os.popen("/usr/bin/ls")
> for line in p.readlines():
> line = line.replace("this", "that")
> print line
> p.close()
>
> > 2. How can I sort and print out a hash.
> >
> > Example in Perl:
> >
> > ex. foreach $string (sort keys %hash) {
> > print("$string = $hash{$string}\n");
> > }

>
> # assuming we have a dict called d
> items = d.items() # get all (key, value) pairs from the dict
> items.sort() # sort them
> for key, value in items:
> print "%s = %s" % (key, value)
>
> HTH,
>
> --
> Hans ((E-Mail Removed))
> http://zephyrfalcon.org/
>
>
>
>



 
Reply With Quote
 
Mike C. Fletcher
Guest
Posts: n/a
 
      10-26-2003
Luther Barnum wrote:
....

>While(<FILE>) {
> chomp;
> if(/(\w+ # Date
> \s+ # Space
> \d+ # Day
> \s+ # Space
> (\w+) # Server
> \s+ # Space
> (\w+)/x) { # Error
>
> $server = $1;
> $error = $2;
>
> $server_totals{$server}++;
> $error_totals{$error}++;
> }
>}
>
>

Haven't tried running this, but should give you an idea of how the
equivalent would work in Python...

import re, sys
server_totals = {}
error_totals = {}
for line in sys.stdin:
line = line.strip()
match = re.match( """
\w+
\s+
\d+
\s+
(\w+)
\s+
(\w+)""", re.X )
if match:
server, error = match.group(1), match.group(2)
server_totals[server] = server_totals.get( server, 0) + 1
error_totals[error] = error_totals.get( server, 0) + 1

HTH,
Mike

_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/




 
Reply With Quote
 
Mark Roach
Guest
Posts: n/a
 
      10-26-2003
On Sun, 26 Oct 2003 02:14:19 +0000, Luther Barnum wrote:
[...]
> Here is another example:
>
> ex:
>
> While(<FILE>) {
> chomp;
> if(/(\w+ # Date
> \s+ # Space
> \d+ # Day
> \s+ # Space
> (\w+) # Server
> \s+ # Space
> (\w+)/x) { # Error
>
> $server = $1;
> $error = $2;
>
> $server_totals{$server}++;
> $error_totals{$error}++;
> }
> }


Whew, I remember now why I ran away from perl fairly quickly. Can you
explain what the above code does? I can see that it iterates over a file
and that somehow it extracts a server name and an error, but I have no idea
what all the strange variables are... I am guessing that is a regex?

If what you are describing is reading from a file formatted like:
2003/10/25 Sat Servername Error10

then something like this might be what you are looking for:

server_totals = {}
error_totals = {}
for line in file('/path/to/logfile'):
line = line.strip()
date, day, server, error = line.split()
server_totals[server] = server_totals.get(server, 0) + 1
error_totals[error] = error_totals.get(error, 0) + 1

-Mark
 
Reply With Quote
 
Luther Barnum
Guest
Posts: n/a
 
      10-26-2003
Actually it could have been written using split. Using regular expressions
makes it a little more flexible. Python has that so that is not the issue
really. It's just that I read that you cannot change a dictionary value and
I wanted to see how it was done in Python. My last question is how do you
iterate over this to get the values by key.

While(<FILE>) {
chomp;
@line = split;
$server = $3;
$error = $4;

$server_totals{$server}++;
$error_totals{$error}++;
}
}


Thanks in advance, you guys have been very helpful

Luther


"Mark Roach" <(E-Mail Removed)> wrote in message
news(E-Mail Removed)...
> On Sun, 26 Oct 2003 02:14:19 +0000, Luther Barnum wrote:
> [...]
> > Here is another example:
> >
> > ex:
> >
> > While(<FILE>) {
> > chomp;
> > if(/(\w+ # Date
> > \s+ # Space
> > \d+ # Day
> > \s+ # Space
> > (\w+) # Server
> > \s+ # Space
> > (\w+)/x) { # Error
> >
> > $server = $1;
> > $error = $2;
> >
> > $server_totals{$server}++;
> > $error_totals{$error}++;
> > }
> > }

>
> Whew, I remember now why I ran away from perl fairly quickly. Can you
> explain what the above code does? I can see that it iterates over a file
> and that somehow it extracts a server name and an error, but I have no

idea
> what all the strange variables are... I am guessing that is a regex?
>
> If what you are describing is reading from a file formatted like:
> 2003/10/25 Sat Servername Error10
>
> then something like this might be what you are looking for:
>
> server_totals = {}
> error_totals = {}
> for line in file('/path/to/logfile'):
> line = line.strip()
> date, day, server, error = line.split()
> server_totals[server] = server_totals.get(server, 0) + 1
> error_totals[error] = error_totals.get(error, 0) + 1
>
> -Mark
>



 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
FAQ 1.4 What are Perl 4, Perl 5, or Perl 6? PerlFAQ Server Perl Misc 0 01-23-2011 05:00 AM
Excel: swithing lower to upper case possible? Sigi Rindler Computer Support 2 11-26-2006 04:11 AM
Norton Protection Centre Firewall Connection Swithing it off Heidi Manway Computer Support 1 11-23-2006 08:23 PM
Swithing Unicode fonts Nik Firefox 3 04-30-2005 11:05 AM
Perl Help - Windows Perl script accessing a Unix perl Script dpackwood Perl 3 09-30-2003 02:56 AM



Advertisments