I'm writing my first python program and I want to run a shell command and get the output. I want to do it in the cleanest possible / most pythonic way. This is what I've got atm. Note: I also want to raise an Exception when there went something worng with execution of the shell command.
def lsCommand():
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out , err = process.communicate()
returnc = process.returncode
if returnc != 0:
raise Exception(err)
else:
return out
What I discovered, is that when I remove the line out , err = process.communicate(), and replace it with time.sleep(4) (<= the ls command doesn't take 4 seconds to complete), The returncode is None, which means that it the subprocess isn't fnished yet. How is this possible? Does the out , err = process.communicate() do an implicit wait() methode call?
def lsCommand():
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
time.sleep(4)
returnc = process.returncode
if returnc != 0:
print returnc
raise Exception(err)
else:
return out
EDIT: I'm using python 2.7
I want to do a longer command sudo find "/media/usb0" -type f -name "*.JPG" | wc -l, but i'm not sure how to call it with Popen, can anyone help?