How do you conver output of "popen('ls')" to a list?

Grant Edwards grante at visi.com
Wed Feb 20 21:56:18 EST 2002


In article <mailman.1014253235.29718.python-list at python.org>, Neil Schemenauer wrote:
> husam wrote:

>> os.listdir('.') gets you all the files in the '.' dircetory. This want
>> work if i want to process some selected files. In contrast to this,
>> "os.popen() allows you to pass arguments like "ls *txt" to retrieve only
>> *.txt files.
> 
> Sorry, that's still not a good argument for two forks and god knows how
> any system calls.  Try this:
> 
>     import glob
>     txt_files = glob.glob("*txt")

In these days of 1.whatever GHz processors, I doubt that a
couple fork/exec combinations matters a lot in most situations.
But, os.system() calls the shell. The shell does god-knows-what
to the arguments, then looks god-knows-where for the
executable.  You can lessen these problems by specifying an
absolute path and quoting the arguments -- though quoting them
properly isn't a trivial problem.

Don't even ask what happens when the wrong shell gets chosen to
start with.  :)

Maybe I'm a bit too paranoid, but using os.system() seems to me
to be begging for problems down the road.  If you explicitly
want shell-command-line semantics then it's cool, but most of
the places I see it used (including in my code) there are more
robust solutions.

Modules to look in when you're tempted to do an os.system():

   shutil
   os.path
   glob
   os
   commands   

If all else fails, os.spawn or os.popen2 are often better
choices than os.system.

I'm done preaching now...

-- 
Grant Edwards                   grante             Yow!  Gibble, Gobble, we
                                  at               ACCEPT YOU...
                               visi.com            



More information about the Python-list mailing list