使用子流程的Python中的大型命令

En_Py

如何使用子流程模块运行此代码?

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

错误:剪切:定界符必须为单个字符

杰夫斯
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()

我正在尝试不使用shell = True

它是确定使用shell=True如果你控制的命令,即,如果你不使用用户输入构建命令。将shell命令视为一种特殊的语言,它使您可以简洁地表达自己的意图(例如用于字符串处理的regex)。与不使用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]]

注意:此处的引号内没有引号(no '" "''":"')。也不同于先前的命令和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

请参阅如何使用subprocess.Popen通过管道连接多个进程?

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章