views:

4308

answers:

4

I've a python script that has to launch a shell command for every file in a dir:

import os

files = os.listdir(".")
for f in files:
    os.execlp("myscript", "myscript", f)

This works fine for the first file, but after the "myscript" command has ended, the execution stops and does not come back to the python script.

How can I do? Do I have to fork() before calling os.execlp()?

+5  A: 

The os.exec*() functions replace the current programm with the new one. When this programm ends so does your process. You probably want os.system().

unbeknown
+14  A: 

subprocess: The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

http://www.python.org/doc/2.5.2/lib/module-subprocess.html

Usage:

import subprocess
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode
A: 

use spawn

import os
os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
M. Utku ALTINKAYA
+5  A: 

You can use subprocess.Popen. There's a few ways to do it:

cmd = ['/run/myscript', '--arg', 'value']
p = subProcess.Popen(cmd, stdout=subprocess.PIPE)
for line in p.stdout:
    print line
p.wait()
print p.returncode

Or, if you don't care what the external program actually does:

cmd = ['/run/myscript', '--arg', 'value']
subProcess.Popen(cmd, stdout=subprocess.PIPE).wait()
Harley