popen function of os and subprocess modules

banu varun.nagpaal at gmail.com
Wed Oct 28 16:26:23 CET 2009


On Oct 28, 3:18 pm, Benjamin Kaplan <benjamin.kap... at case.edu> wrote:
> On Wed, Oct 28, 2009 at 9:39 AM, 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()
>
> So, here's what you're doing manually.
> 1) Open up a terminal, type "cd /etc". And then close that terminal
> 2) Open up a new terminal, type "ls -l" and wonder why it's not in /etc
>
> > Can anyone suggest me how to fix this simple script? Also what is the
> > use of read(), readlines() and write() functions?
>
> The os and os.path modules contain higher-level functions than popen.
> Such as os.listdir and os.chdir (if you really want to change the
> current directory for the program).
>
> popen returns a file object. In your case, because you opened it in
> write mode, it's stdin so write will send things to the program
> (assuming it reads from stdin), and read/readlines are useless. If you
> were to open it in read mode, pr would be stdout and you would use
> pr.read() or pr.readlines() to get your directory list instead of
> having it print out to the terminal. Or you could use os.popen2 or
> subprocess.Popen (the newer, preferred, more complicated way) and get
> both at once.
>
>
>
> > 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?
>
> For this example, where you just want to print stuff out,  just use
> subprocess.call(['ls','-l'])
>
> For more complicated examples:
>
> pr = subprocess.Popen(['ls','-l'],stdout=subprocess.PIPE)
> file_list = pr.stdout.readlines()
>
>
>
> > Regards
> > Varun
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
>

Thanks for reply Benjamin.I got it now.



More information about the Python-list mailing list