How to spawn a program with redirection as it parameter

TH Lim sshark97 at hotmail.com
Thu Jul 10 12:48:45 EDT 2003


Thanks Donn, ur explaination sure put things into perspective. before
this, i was wandering why ">>" works in os.system() and not in
spawn().well, now i know why.

"Donn Cave" <donn at drizzle.com> wrote in message news:<1057291400.926913 at yasure>...
> Quoth sshark97 at hotmail.com (TH Lim):
> | How do I do a simple thing like  /bin/cat myfile.txt >> yourfile.txt
> | in unix? I tried with the script shown below but not successful. Am
> | doing it right? Pls. advise. thank you.
> |
> | #!/usr/bin/python
> | import os
> | os.spawnl(os.P_WAIT, "/bin/cat" , "/bin/cat", "myfile.txt >>
> | yourfile.txt")
> | print "Done"
> 
> No, the '>>' operator belongs to the shell, and in spawnl there
> is no shell.  As another followup observes, if you want a shell,
> you can use system() -
>   os.system('cat myfile.txt >> yourfile.txt')     is about the same as
>   os.spawnl(os.P_WAIT, '/bin/sh', 'sh', '-c', 'cat myfile.txt >> yourfile.txt')
> 
> Sometimes we would rather avoid the shell, because there's a risk
> that when it re-evaluates the command parameters they will come
> out different than we intend.  In that case, there isn't any standard
> function, you have to write your own.  Off the top of my head, maybe
> try something like
> 
>   def spawnvio(w, file, cmd, iodx):
>       pid = os.fork()
>       if pid:
>           if w == os.P_WAIT:
>               p, s = os.waitpid(pid, 0)
>               return s
>           else:
>               return pid
>       else:
>           try:
>               # Perform redirections
>               for n, u in iodx:
>                   if n != u:
>                       os.dup2(n, u)
>                       os.close(n)
>               os.execve(file, cmd, os.environ)
>           finally:
>               os._exit(113)
> 
>   yrf = os.open('yourfile.txt', os.O_APPEND|os.O_CREAT)
>   spawnvio(os.P_WAIT, '/bin/cat', ['cat', 'myfile.txt'], [(yrf, 1)])
>   os.close(yrf)
> 
> 	Donn Cave, donn at drizzle.com




More information about the Python-list mailing list