2010-05-14 19 views
44

Ich habe ein Skript, wo ich mit einem Shell-Befehl popen. Das Problem ist, dass das Skript nicht wartet, bis dieser Popen-Befehl beendet ist und sofort weiter geht.Python popen Befehl. Warte, bis der Befehl beendet ist

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

Wie kann ich meinem Python-Skript sagen, dass es warten soll, bis der Shell-Befehl beendet ist?

Antwort

65

Je nachdem, wie Sie Ihr Skript bearbeiten möchten, haben Sie zwei Möglichkeiten. Wenn Sie möchten, dass die Befehle während der Ausführung blockiert und nicht ausgeführt werden, können Sie einfach subprocess.call verwenden.

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

Wenn Sie Dinge tun wollen, während es ausgeführt wird oder Futtermittel Dinge in stdin, können Sie communicate nach dem popen Aufruf verwenden.

#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 

Wie in der Dokumentation angegeben, kann wait Deadlock, so kommunizieren ratsam ist.

+0

Überprüfen Sie die Dokumente auf [subprocess.call] (http://docs.python.org/library/subprocess.html#convenience-functions) – thornomad

5

Was Sie suchen, ist die wait Methode.

+0

Aber wenn ich schreibe. om_points = os.popen (data [ "om_points"] + "> "+ diz [ 'd'] +"/ points.xml", "w") warten ( ) erhalte ich diesen Fehler: Traceback (jüngste Aufforderung zuletzt): File "./model_job.py", Zeile 77, in om_points = os.popen (data [ "om_points"] + ">" + diz ['d'] + "/ points.xml", "w"). wait() AttributError: 'Datei' Objekt hat kein Attribut 'Warten' Was ist das Problem? Danke nochmal. – michele

+9

Sie haben nicht auf den angegebenen Link geklickt. 'wait' ist eine Methode der' subprocess' Klasse. –

+0

warten kann Deadlock, wenn der Prozess in stdout schreibt und niemand liest es – ansgri

5

Sie können subprocess verwenden, um dies zu erreichen.

import subprocess 

#This command could have multiple commands separated by a new line \n 
some_command = "export PATH=$PATH://server.sample.mo/app/bin \n customupload abc.txt" 

p = subprocess.Popen(some_command, stdout=subprocess.PIPE, shell=True) 

(output, err) = p.communicate() 

#This makes the wait possible 
p_status = p.wait() 

#This will give you the output of the command being executed 
print "Command output: " + output 
Verwandte Themen