Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #17014

Re: subprocess question

References <20111212043933.BCJ1L.23648.root@cdptpa-web38-z02.mail.rr.com>
Date 2011-12-11 22:02 -0800
Subject Re: subprocess question
From Chris Rebert <clp2@rebertia.com>
Newsgroups comp.lang.python
Message-ID <mailman.3531.1323669745.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, Dec 11, 2011 at 8:39 PM,  <jyoung79@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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: subprocess question Chris Rebert <clp2@rebertia.com> - 2011-12-11 22:02 -0800
  Re: subprocess question Nobody <nobody@nowhere.com> - 2011-12-12 15:16 +0000

csiph-web