On Sun, Dec 11, 2011 at 8:39 PM, <jyoun...@kc.rr.com> wrote: > Wondering if anyone could shed some light on the subprocess module? I'll > admit I'm not that great at the shell. > > If I was wanting to get the size of the trash (on OS X), I could use: > >>>> os.system('du -sh ~/.Trash/') > 11M /Users/jay/.Trash/ > 0 > > Which gives me what I want. However, I've been reading that it's better to > use subprocess. I did a test like so, but is this a good way to do this? > >>>> import subprocess >>>> p = subprocess.Popen(['du', '-sh'], cwd='/Users/jay/.Trash/', >>>> stdout=subprocess.PIPE) >>>> out, err = p.communicate() >>>> out > ' 11M\t.\n'
You might prefer to use subprocess.check_output(); it slightly simplifies your code: http://docs.python.org/library/subprocess.html#subprocess.check_output > And another question - why can't I use the tilde as a shortcut to the home > directory? Because ~ is interpolated by the shell and `subprocess` does not use the shell by default for reasons that include efficiency and security. You can expand ~ yourself using os.path.expanduser(): http://docs.python.org/library/os.path.html#os.path.expanduser Alternatively, you can opt to use the shell by passing shell=True as an argument. Cheers, Chris -- http://rebertia.com -- http://mail.python.org/mailman/listinfo/python-list