2010-05-14 25 views
44

Bir kabuk komutunu kullanarak başlattığım bir komut dosyası var. Sorun, komut dosyasının bu popen komutu bitene kadar beklememesi ve hemen devam etmesidir.Python popen komutu. Komut bitene kadar bekleyin

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

Kabuk komutunun bitmesini beklemek için Python betiğime nasıl anlarım?

cevap

65

Komut dosyanızı nasıl çalıştırmak istediğinize bağlı olarak iki seçeneğiniz vardır. Komutların yürütülürken herhangi bir şey yapmasını engellemek istemiyorsanız, subprocess.call'u kullanabilirsiniz. Eğer stdin içine o yürütülürken şeyleri veya besleme şeyler yapmak istiyorsanız

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

, sen popen çağrısından sonra communicate kullanabilirsiniz. belgelerinde belirtildiği gibi

#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 

, wait kilitlenmeye, bu nedenle tavsiye edilir iletişim kurabilir.

+0

[subprocess.call] adresindeki belgelere göz atın (http://docs.python.org/library/subprocess.html#convenience-functions) – thornomad

5

Aradığınız ürün wait yöntemidir.

+0

Ama tip ise. om_points = os.popen (veriler: [ "om_points"] + "> "+ diz [ 'd'] +"/ points.xml", "W") bekleyin () bu hatayı alırsınız: traceback (en son çağrı son): Dosya "./model_job.py", çizgi 77, + ">" + diz [ "om_points"] om_points = os.popen (veri içinde ['d'] + "/ points.xml", "w") wait() AttributeError: 'file' nesnesi 'wait' özelliğine sahip değil Sorun nedir? Tekrar teşekkürler. – michele

+9

Sağladığım bağlantıyı tıkladınız. 'wait', 'subprocess' sınıfının bir yöntemidir. –

+0

, işlem stdout'a yazıyorsa ve kimse bunu okumazsa, kilitlenme bekleyebilir – ansgri

5

Bunu gerçekleştirmek için subprocess özelliğini kullanabilirsiniz.

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 
İlgili konular