[Tutor] File copying - best way?

Michael P. Reilly arcege@speakeasy.net
Sun, 5 Aug 2001 09:53:44 -0400


On Sun, Aug 05, 2001 at 08:47:00AM -0400, fleet@teachout.org wrote:
> - but I have no clue how to use it.  Would this have allowed me to test:
> 
> os.popen("ls *.jpg")
> 
> if it found no jpg files?

Much like a C program, you need to get the exit status value and
decode it.  The close() method returns the exit status.

def list_jpegs():
  class StoppedProgram(Exception):
    pass
  class ProgramTerminated(Exception):
    pass
  import os
  f = os.popen("ls -1 *.jpg", "r")
  files = f.readlines()

  stat = f.close()  # this is what is returned by wait(2)
  # if rc is false (0 or None) then everything is fine
  if not rc:
    rc = 0

  # program terminated normally, but possibly with error
  elif os.WIFEXITED(stat):
    rc = os.WEXITSTATUS(stat)

  # was cntl-Z type or something similar?
  elif os.WIFSTOPPED(stat):
    raise StoppedProgram(os.WSTOPSIG(stat))

  # the program was abnormally terminated, cntl-C or logout or kill
  elif os.WIFSIGNALLED(stat):
    raise ProgramTerminated(os.WTERMSIG(stat))

  return rc, files  # return exit status and list

You could also raise an exception if rc is true.  A design flaw in how
Python handles these things is that the os.W* functions cannot take
the None value returned by most of the functions (like popen().close()
and os.wait()) that are to pass the values to them.  So you need to
check the value before passing them to os.WIFEXITED, os.WSTOPSIG, etc..
For the most part, if the result is false, then you know things are fine.

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |