2010-12-10 23 views

cevap

34
>>> import subprocess 
>>> cmd = [ 'echo', 'arg1', 'arg2' ] 
>>> output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0] 
>>> print output 
arg1 arg2 

>>> 

Alt işlemlerin kullanılmasında bir hata var.PIPE. büyük çıkış kullanım Bunun için: onlar önerdiği gibi

import subprocess 
import tempfile 

with tempfile.TemporaryFile() as tempf: 
    proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf) 
    proc.wait() 
    tempf.seek(0) 
    print tempf.read() 
+0

sen benim kurtarıcı komutları kullanmaktır !!! günlerdir böyle bir şey arıyordum! teşekkür ederim! –

14

subprocess module kullanın.

pipe = Popen("pwd", shell=True, stdout=PIPE).stdout 
output = pipe.read() 

Python 2.7'de check_output() işlevini de kullanabilirsiniz.

4

Sen subprocess içinde Popen kullanabilirsiniz. şu değil edilir os ile

, aşağıda gibidir:

import os 
a = os.popen('pwd').readlines() 
+0

Bu işe yaramıyor. 'Popen' nesnesinde' readlines() 'yöntemi yoktur. –

+0

Bunu işaretlediğiniz için teşekkürler, sadece os.popen – gerry

+3

'os.popen' için çalışır; altprocess.Popen' lehine önerilmemektedir. –

0

kolay yolu kütüphane

import commands 
print commands.getstatusoutput('echo "test" | wc') 
+2

Komut modülünü nereden alıyorsunuz? Python3 için piponda görünmüyor. – Shule