2014-03-01 22 views
0

我如何使用子進程模塊來運行此代碼?使用子進程的Python中的大型命令

commands.getoutput('sudo blkid | grep 'uuid' | cut -d " " -f 1 | tr -d ":"') 

我已經試過,但它並沒有在所有

out_1 = subprocess.Popen(('sudo', 'blkid'), stdout=subprocess.PIPE) 
out_2 = subprocess.Popen(('grep', 'uuid'), stdin=out_1.stdout, stdout=subprocess.PIPE) 
out_3 = subprocess.Popen(('cut', '-d', '" "', '-f', '1'), stdin=out_2.stdout, stdout=subprocess.PIPE) 
main_command = subprocess.check_output(('tr', '-d', '":"'), stdin=out_3.stdout) 

main_command 

錯誤的工作:切:分隔符必須是單個字符

+0

它能做什麼 - 你有錯誤的訊息張貼 – PyNEwbie

+0

錯誤:斬:分隔符必須是單個字符 –

+0

你知道那'grep'uuid'|剪下-d「」-f 1 | tr -d「:」'可以用一個命令替換:'awk'/ uuid/{print gsub(「:」,「」,$ 1)}'' – devnull

回答

1
from subprocess import check_output, STDOUT 

shell_command = '''sudo blkid | grep 'uuid' | cut -d " " -f 1 | tr -d ":"''' 
output = check_output(shell_command, shell=True, stderr=STDOUT, 
         universal_newlines=True).rstrip('\n') 

順便說一句,它除非使用grep -i我的系統上沒有返回。在後者的情況下,它返回設備。如果這是你的意圖,那麼你可以使用不同的命令:

from subprocess import check_output 

devices = check_output(['sudo', 'blkid', '-odevice']).split() 

I'm trying not to use shell=True

這是確定使用shell=True如果你控制的命令,即,如果你不使用用戶輸入構建命令。考慮shell命令作爲一種特殊的語言,它允許你簡潔地表達你的意圖(比如正則表達式用於字符串處理)。這是更可讀那麼幾行代碼不使用shell:

from subprocess import Popen, PIPE 

blkid = Popen(['sudo', 'blkid'], stdout=PIPE) 
grep = Popen(['grep', 'uuid'], stdin=blkid.stdout, stdout=PIPE) 
blkid.stdout.close() # allow blkid to receive SIGPIPE if grep exits 
cut = Popen(['cut', '-d', ' ', '-f', '1'], stdin=grep.stdout, stdout=PIPE) 
grep.stdout.close() 
tr = Popen(['tr', '-d', ':'], stdin=cut.stdout, stdout=PIPE, 
      universal_newlines=True) 
cut.stdout.close() 
output = tr.communicate()[0].rstrip('\n') 
pipestatus = [cmd.wait() for cmd in [blkid, grep, cut, tr]] 

注:裏面有此報價不含引號(無'" "''":"')。也不像前面的命令和commands.getoutput(),它不捕獲stderr。

plumbum提供了一些語法糖:

from plumbum.cmd import sudo, grep, cut, tr 

pipeline = sudo['blkid'] | grep['uuid'] | cut['-d', ' ', '-f', '1'] | tr['-d', ':'] 
output = pipeline().rstrip('\n') # execute 

How do I use subprocess.Popen to connect multiple processes by pipes?

0

通過你的命令,像這樣的字符串:

main_command = subprocess.check_output('tr -d ":"', stdin=out_3.stdout) 

如果您有多個命令並且想要逐個執行,請將它們傳遞爲列表:

main_command = subprocess.check_output([comand1, command2, etc..], shell=True) 
+0

我試圖不使用shell = True –

+0

-1:第一個參數有不同的含義。 – jfs

相關問題