gpt4 book ai didi

python - 来自 Python 的 awk : wrong subprocess arguments?

转载 作者:行者123 更新时间:2023-12-01 16:10:59 25 4
gpt4 key购买 nike

我需要在 Python 中运行以下(有效的)命令:

ip route list dev eth0 | awk ' /^default/ {print $3}'

使用 subprocess,我必须执行以下操作:

first = "ip route list dev eth0"
second = "awk ' /^default/ {print $3}'"
p1 = subprocess.Popen(first.split(), stdout=subprocess.PIPE)
p2 = subprocess.Popen(second.split(), stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]

p2 出了点问题。我得到:

>>> awk: cmd. line:1: '
awk: cmd. line:1: ^ invalid char ''' in expression

我该怎么办?在终端上它运行完美。

最佳答案

split 在任何空格处拆分,包括单引号参数内的空格。如果确实需要,请使用 shlex.split:

import shlex
p2 = subprocess.Popen(shlex.split(second), stdin=p1.stdout, stdout=subprocess.PIPE)

然而,直接指定命令通常更有意义:

first = ['ip', 'route', 'list', 'dev', 'eth0']
second = ['awk', ' /^default/ {print $3}']
p1 = subprocess.Popen(first, stdout=subprocess.PIPE)
p2 = subprocess.Popen(second, stdin=p1.stdout, stdout=subprocess.PIPE)

关于python - 来自 Python 的 awk : wrong subprocess arguments?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15414244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com