Is pyton for me?

Andrew Dalke dalke at dalkescientific.com
Fri Jun 10 00:18:10 EDT 2005


Mark de la Fuente wrote:
> Here is an example of the type of thing I would like to be able to do. 
> Can I do this with python?  How do I get python to execute command line
> functions?
 ...
> # simple script to create multiple sky files.
> 
> foreach hour (10 12 14)
> 		gensky 3 21 $hour > sky$hour.rad
> end

Dan Bishop gave one example using os.system.  The important
thing to know is that in the shell all programs can be used
as commands while in Python there isn't a direct connection.
Instead you need to call a function which translates a
request into something which calls the command-line program.

There are several ways to do that.  In Python before 2.4
the easiest way is with os.system(), which takes the command-line
text as a string.  For example,

import os
os.system("gensky 3 21 10 > sky10.rad")

You could turn this into a Python function rather easily

import os

def gensky(hour):
  os.system("gensky 3 21 %d > sky%d.rad" % (hour, hour))

for hour in (10, 12, 14):
  gensky(hour)


Python 2.4 introduces the subprocess module which makes it
so much easier to avoid nearly all the mistakes that can
occur in using os.system().  You could replace the 'gensky'
python function with

import subprocess
def gensky(hour):
  subprocess.check_call(["gensky", "3", "21", str(hour)],
                       stdout = open("sky%d.rad" % (hour,), "w"))


The main differences here are:
 - the original code didn't check the return value of os.system().
It should do this because, for example, the gensky program might
not be on the path.  The check_call does that test for me.

 - I needed to do the redirection myself.  (I wonder if the
subprocess module should allow

  if isinstance(stdout, basestring):
    stdout = open(stdout, "wb")

Hmmm....)


> If I try and do a gensky command from the python interpreter or within a
> python.py file, I get an error message:
> 
> NameError: name ‘gensky’ is not defined

That's because Python isn't set up to search the command path
for an executable.  It only knows about variable names defined
in the given Python module or imported from another Python
module.

> If anyone has any suggestions on how to get python scripts to execute
> this sort of thing, what I should be looking at, or if there is
> something else I might consider besides python, please let me know.

You'll have to remember that Python is not a shell programming
language.  Though you might try IPython - it allows some of the
things you're looking for, though not all.

You should also read through the tutorial document on Python.org
and look at some of the Python Cookbook..  Actually, start with
  http://wiki.python.org/moin/BeginnersGuide

				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list