Getting to know Python

Thomas A. Bryan tbryan at arlut.utexas.edu
Sat Jul 3 00:16:17 EDT 1999


Arnaldo wrote:

> In the mean-time I'm eager to have with the interactive interpreter.
> How do I access the shell from the interpreter to enter commands like
> ,clear, ls, cp, etc.
> Is it posible, how do I do that?

Yes.  os.system() or os.popen()
Of course, many of these commands are available in the standard 
Python library.

For exmple, os.listdir() and shutil.copy() for ls and cp.

Python 1.5.2 (#1, Apr 18 1999, 16:03:16)  [GCC pgcc-2.91.60 19981201 
(egcs-1.1.1  on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import os
>>> retval = os.system('ls /')
bin  boot  dev  etc  home  lib  lost+found  misc  mnt  opt  proc
  root  sbin  tmp  usr  var
>>> cmd = os.popen('ls /')
>>> output = cmd.readlines()
>>> cmd.close()
>>> output
['bin\012', 'boot\012', 'dev\012', 'etc\012', 'home\012', 'lib\012', 
'lost+found\012', 'misc\012', 'mnt\012', 'opt\012', 'proc\012', 
'root\012', 'sbin\012', 'tmp\012', 'usr\012', 'var\012']

If you're playing in the interpreter, learn to use the doc strings 
for the modules that have them:

>>> print os.system.__doc__
system(command) -> exit_status
Execute the command (a string) in a subshell.
>>> print os.popen.__doc__
popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.

To find out what's available, do a dir(os).

You may also want to read through/download the library reference from 
www.python.org

Here's a handy function...you'll probably want to modify it so that 
it writes to a file unless you have a lot of "history" on your terminal
window.

def get_docs(modulename):
    for el in dir(eval(modulename)):
        try:
            print el
            exec('print %s.%s.__doc__' % (modulename,el))
        except: #catch all exceptions
            print '%s has no __doc__' % el

#for example
import string
get_docs('string')




More information about the Python-list mailing list