2014-03-01 20 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

相关问题