Saturday, December 29, 2007

fun with python: running programs using popen

Yesterday, I run unix command, by using the command modules.

It turn out that there is another way, and more importantly cross platform. So it will run on windows.

Python provides a set of modules for generic operating system service. In the os module. And in it is a popen() function. Which can be used to call program,

so to run a program using popen, using "ls ~" as an example, it can be many program:

import os
comm=os.popen("ls ~")
for line in comm.read():
print line

which will print the output. But for some reason, cat a file don't work. You don't really need to print an output, you can just use it to run a program.

5 comments:

  1. Anonymous12:35 PM

    for line in comm.read():
    print line






    looks... the .read() is necessary!

    ReplyDelete
  2. Yes you are actually RIGHT!!!!!!

    Thanks for inform me.

    ReplyDelete
  3. I hope you still read old comments...

    I can't get output to work at all. Let's use ffmpeg as an example...

    import os

    comm=os.popen("ffmpeg -i mymovie.avi -b 2048k -vcodec libxvid -acodec aac mymovie.mov")

    while 1:
    for line in comm.read():
    print line

    Is that how I would get the console output to show up? Because it wont work... what am I doing wrong?

    ReplyDelete
  4. honestly i am not really sure,
    will check out.

    why you put in a infinite loop anyway, don't think it is needed.

    ReplyDelete
  5. I dunno, it seems that, once python opens ffmpeg, python doesn't wait for ffmpeg to finish, but just goes on to the other lines, so it prints nothing, as there is no output yet I guess. Though, with the infinite loop, it crashes :P

    ReplyDelete