popen function of os and subprocess modules

Sean DiZazzo half.italian at gmail.com
Thu Oct 29 02:26:03 CET 2009


On Oct 28, 7:15 am, banu <varun.nagp... at gmail.com> wrote:
> On Oct 28, 3:02 pm, Jon Clements <jon... at googlemail.com> wrote:
>
>
>
> > On 28 Oct, 13:39, banu <varun.nagp... at gmail.com> wrote:
>
> > > Hi,
> > > I am a novice in python. I was trying to write a simple script on
> > > Linux (python 3.0) that does the following
>
> > > #cd directory
> > > #ls -l
>
> > > I use the following code, but it doesn't work:
>
> > > import os
> > > directory = '/etc'
> > > pr = os.popen('cd %s' % directory,'w')
> > > pr.close()
> > > pr = os.popen('ls -l','w')                                      #
> > > prints the content of present folder and not '/etc'
> > > pr.close()
>
> > > Can anyone suggest me how to fix this simple script? Also what is the
> > > use of read(), readlines() and write() functions?
>
> > > Now, I also read in the online python documentation that os.popen is
> > > deprecated and no longer recommended in pyhton 3.0. Instead they ask
> > > to use subprocess.popen. I am not able to figure out how to accomplish
> > > my task with subprocess.poepn also. Can anyone suggest please?
>
> > > Regards
> > > Varun
>
> > If you're only trying to get the contents of a directory, there are
> > more suitable functions - you don't need a separate process. The popen*
> > () commands are deprecated.
>
> > Try using os.listdir() - can't remember off the top of my head if
> > that's been moved to os.path.listdir() in the 3.* series, but a read
> > of the doc's will set you straight.
>
> > Ditto for read() and write().
>
> > If you describe what you're trying to achieve, maybe we can help more.
>
> > Also, if you're using 3.0, may I suggest moving to 3.1?
>
> > hth,
>
> > Jon.
>
> Thanks for the reply Jon
> Basically I need to move into a folder and then need to execute some
> shell commands(make etc.) in that folder. I just gave 'ls' for the
> sake of an example. The real problem I am facing is, how to stay in
> the folder after popen('cd directory') finishes. It seems trivial, but
> I am not able to do it.
>
> Varun

Use subprocess.Popen() with it's "cwd" argument.  Something like:

import subprocess
p = subprocess.Popen(["ls","-l"] stdout=subprocess.PIPE, cwd="/etc")

print p.stdout.read()

~Sean



More information about the Python-list mailing list