Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python popen command. Wait until the command is finished

I have a script where I launch with popen a shell command. The problem is that the script doesn't wait until that popen command is finished and go continues right away.

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

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

like image 590
michele Avatar asked May 14 '10 20:05

michele


People also ask

How do you wait for Popen to finish?

A Popen object has a . wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status). If you use this method, you'll prevent that the process zombies are lying around for too long. (Alternatively, you can use subprocess.

Does subprocess wait for command to finish?

subprocess. run() is synchronous which means that the system will wait till it finishes before moving on to the next command.

Does Popen need to be closed?

Popen do we need to close the connection or subprocess automatically closes the connection? Usually, the examples in the official documentation are complete. There the connection is not closed. So you do not need to close most probably.

What is Popen command?

DESCRIPTION. The popen() function shall execute the command specified by the string command. It shall create a pipe between the calling program and the executed command, and shall return a pointer to a stream that can be used to either read from or write to the pipe.


1 Answers

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 plus that you can send commands to process 

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

like image 74
unholysampler Avatar answered Oct 14 '22 04:10

unholysampler