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?
它能做什么 - 你有错误的讯息张贴 – PyNEwbie
错误:斩:分隔符必须是单个字符 –
你知道那'grep'uuid'|剪下-d“”-f 1 | tr -d“:”'可以用一个命令替换:'awk'/ uuid/{print gsub(“:”,“”,$ 1)}'' – devnull