How to spawn a program with redirection as it parameter

Donn Cave donn at
Fri Jul 4 06:03:22 CEST 2003

Quoth sshark97 at (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
              return pid
              # Perform redirections
              for n, u in iodx:
                  if n != u:
                      os.dup2(n, u)
              os.execve(file, cmd, os.environ)

  yrf ='yourfile.txt', os.O_APPEND|os.O_CREAT)
  spawnvio(os.P_WAIT, '/bin/cat', ['cat', 'myfile.txt'], [(yrf, 1)])

	Donn Cave, donn at

More information about the Python-list mailing list