Jump to content

Python: Trapping Output From System Call


TheUsualAlex

Recommended Posts

Is this a python question?

ie myVar = os.system(blah)

And the result is 0 or 1 but the function called does a whole heap of stuff?

I think you are stuck you really need a function that will return a string then you can grab that. Might be wrong though. What function are you actually trying to call?

Link to comment
Share on other sites

Capturing the output of a subprocess is not called globbing. Globbing is a method for string matching using '*' and '?'. This is often used in the shell, so that globbing often refers to the matching of file names.

Capturing the output of an executable is done easily with Popen instead of os.system. Take a look at the following example, that calls ls -lh and afterwards prints the result line by line:

from subprocess import Popen, PIPE, STDOUT

process = Popen(('ls', '-lh'), stdout=PIPE, stderr=STDOUT)
for line in process.stdout:
	print line

On the other side, if you only want a list of files (globbing), you can use the glob module

import os, glob

searchDir = "."
listOfFiles = glob.glob(os.path.join(searchDir,"*.*"))
for f in listOfFiles:
  print f

Link to comment
Share on other sites

Wow! Thanks Frank! That was exactly what I was looking for. It never occured to me to look into the subprocess module -- it's making a bit more sense now. Thanks for clearifying the term "globbing" also. :) I got confused with this term from back when I was learning Perl several years back. :D

Hi Simon, I was just trying to call the Cygwin program (cygpath) to retrieve correctly formatted path. cygpath will spit a line of string to stdout (assuming no error). Though os.system() will do the correct thing, but it won't capture what was spitted out from cygpath. In perl it's the same as doing `` to capture that stdout.

Thanks again!

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...