tags:

views:

418

answers:

3

Hi, I have a script where I launch with popen a shell command. The problem is that the script don't wait that popen command is finished and go forward.

om_points = os.popen(command, "w") .....

How can I tell to my python script to wait until the shell command has finished?

Thanks.

+1  A: 

What you are looking for is the wait method.

Olivier
But if I type: om_points = os.popen(data["om_points"]+" > "+diz['d']+"/points.xml", "w").wait()I receive this error:Traceback (most recent call last): File "./model_job.py", line 77, in <module> om_points = os.popen(data["om_points"]+" > "+diz['d']+"/points.xml", "w").wait()AttributeError: 'file' object has no attribute 'wait'What is the problem?Thanks again.
michele
You did not click on the link I provided. `wait` is a method of the `subprocess` class.
Olivier
+5  A: 

Depending on how you want to work your script you have two options. If you want the commands to block and not do anything while it is executing, you can just use subprocess.call.

#start and block until done
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])

If you want to do things while it is executing or feed things into stdin, you can use communicate after the popen call.

#start and process things, then wait
p = subprocess.Popen(([data["om_points"], ">", diz['d']+"/points.xml"])
print "Happens while running"
p.communicate() #now wait

As stated in the documentation, wait can deadlock, so communicate is advisable.

unholysampler
Check out the docs on [subprocess.call](http://docs.python.org/library/subprocess.html#convenience-functions)
thornomad
A: 

Sorry but I have not understand how to modify my script.

print ("\n .............LOADING OM_POINTS "+ data['om_points']) om_points = os.popen(data["om_points"]+" > "+diz['d']+"/points.xml", "w").wait()

// .....other command

I want that the script wait until os.popen command has finished the command execution.

So when os.popen command is finished (it stamps to the shell some output) the script execute the other command.

Thanks.

michele
`os.popen` has been [depreciated](http://docs.python.org/library/os.html#os.popen). You should be using [`subprocess`](http://docs.python.org/library/subprocess.html#module-subprocess) and then you will be able to use `communicate`.
unholysampler
Can you write me an example?Sorry but I'm not very expert.Thanks.
michele
I cleaned up my initial answer some so you can see an example of call and communicate.
unholysampler