2

我需要在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

我该怎么办?在终端上它工作得很好。

4

2 回答 2

13

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)
于 2013-03-14T16:06:13.873 回答
3

不是最佳解决方案,但在等待最佳答案时,您仍然可以这样做:

cmd = "ip route list dev eth0 | awk ' /^default/ {print $3}'"
p2 = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
于 2013-03-14T16:08:03.130 回答