Newbie Questions: Swithing from Perl to Python

Hans Nowak hans at zephyrfalcon.org
Sat Oct 25 21:18:30 EDT 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 (hans at zephyrfalcon.org)
http://zephyrfalcon.org/







More information about the Python-list mailing list