到目前为止,我有一个代码可以过滤掉除网关 IP 之外的所有内容 (route -n | awk '{if($4=="UG")print $2}'
),但是我'我试图弄清楚如何将其通过管道传输到 Python 中的变量。这是我得到的:
import shlex;
from subprocess import Popen, PIPE;
cmd = "route -n | grep 'UG[ \t]' | awk '{print $2}'";
gateway = Popen(shlex.split(cmd), stdout=PIPE);
gateway.communicate();
exit_code = gateway.wait();
有什么想法吗?
注意:我是新手。
最佳答案
无论好坏,您的 cmd
使用 shell 管道。要在子进程中使用 shell 功能,必须设置 shell=True
:
from subprocess import Popen, PIPE
cmd = "/sbin/route -n | grep 'UG[ \t]' | awk '{print $2}'"
gateway = Popen(cmd, shell=True, stdout=PIPE)
stdout, stderr = gateway.communicate()
exit_code = gateway.wait()
或者,可以保留 shell=False
,消除管道,并在 python 中进行所有字符串处理:
from subprocess import Popen, PIPE
cmd = "/sbin/route -n"
gateway = Popen(cmd.split(), stdout=PIPE)
stdout, stderr = gateway.communicate()
exit_code = gateway.wait()
gw = [line.split()[1] for line in stdout.decode().split('\n') if 'UG' in line][0]
由于 shell 处理的变幻莫测,除非有特定需要,否则最好避免 shell=True
。
关于python - 将变量设置为网关 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30205842/