我需要在 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
我该怎么办?在终端上它完美运行。
答案 0 :(得分:9)
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)
答案 1 :(得分:3)
不是最佳解决方案,但在等待最佳答案时,您仍然可以这样做:
cmd = "ip route list dev eth0 | awk ' /^default/ {print $3}'"
p2 = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)