【问题标题】:How to split up the command here for using subprocess.Popen()如何在此处拆分命令以使用 subprocess.Popen()
【发布时间】:2014-12-17 19:19:16
【问题描述】:
ip = subprocess.Popen(["/sbin/ifconfig $(/sbin/route | awk '/default/ {print $8}') | grep \"inet addr\" | awk -F: '{print $2}' | awk \'{print $1}\'"], stdout=subprocess.PIPE)

我不确定在哪里放置逗号来分隔它们以使用 subprocess.Popen 使用此命令。有人知道吗?

【问题讨论】:

  • 使用shlex.split
  • 具体怎么用?
  • 只需导入模块并执行shlex.split('your long command')

标签: python command subprocess


【解决方案1】:

您正在使用 shell 功能(管道),因此您应该将其作为单个字符串(而不是列表)与 shell=True 一起传递,而不是拆分命令。

ip = subprocess.Popen("/sbin/ifconfig $(/sbin/route | awk '/default/ {print $8}') | grep \"inet addr\" | awk -F: '{print $2}' | awk \'{print $1}\'",
    shell=True,
    stdout=subprocess.PIPE)

【讨论】:

  • 一定要试试看!
【解决方案2】:

这是我的推荐。

使用此内容创建一个文件 - 将其命名为 'route-info' 并使其可执行:

#!/bin/sh

/sbin/ifconfig $(/sbin/route | awk '/default/ {print $8}') |
    grep "inet addr" |
    awk -F: '{print $2}' |
    awk '{print $1}'

在你的 python 程序中,使用:

ip = subprocess.Popen(["/path/to/route-info"], stdout=subprocess.PIPE)

那么您不必担心引用字符,您可以独立测试route-info 脚本以确保其正常工作。

脚本route-info 不接受任何命令行参数,但如果这样做,您将通过以下方式传递它们:

ip = subprocess.Popen(["/path/to/route-info", arg1, arg2, ...], stdout=subprocess.PIPE)

【讨论】:

  • 超级!拯救了我的一天。你能否告诉我什么在 Mac 上可以工作,以及这个路由信息如何将 Mac 与我将用于 CentOS 的上述区别开来?
  • 要在 OSX 上查找默认路由,请使用 route -n get default。我认为您应该为每个操作系统创建特定版本并在安装脚本时安装正确的版本 - 即在安装时确定操作系统,而不是在运行时。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-04
  • 2016-01-31
  • 1970-01-01
  • 2013-03-06
相关资源
最近更新 更多