【问题标题】:python formatting return value of subprocesspython格式化子进程的返回值
【发布时间】:2015-06-14 04:30:04
【问题描述】:

我正在尝试在 Python 2.6.6 上将系统的路由表(用于接口)放入 python 列表中进行解析;但我似乎无法解决为什么将整个结果存储到一个变量中。

循环似乎一次迭代一个字符,而我想要的行为是一次一行。

我得到的是一个字符;下面的简短示例...

1
0
.
2
4
3

我希望线路返回的内容;所以我可以对每一行运行其他命令..

10.243.186.1    0.0.0.0         255.255.255.255 UH        0 0          0 eth0
10.243.188.1    0.0.0.0         255.255.255.255 UH        0 0          0 eth0
10.243.184.0    10.243.186.1    255.255.255.128 UG        0 0          0 eth0

下面是代码...

def getnet(int):
    int = 'eth0' ####### for testing only
    cmd = ('route -n | grep ' + int)
    routes = subprocess.Popen([cmd], shell=True, stdout=subprocess.PIPE)
    routes, err = routes.communicate()
    for line in routes:
        print line

【问题讨论】:

    标签: subprocess python-2.6


    【解决方案1】:

    routes 在您的情况下是一个字节字符串,其中包含 shell 命令的 entire 输出。 for character in astring 语句一次生成一个字符,如您问题中的示例所示。要将行改为字符串列表,请调用 lines = all_output.splitlines():

    from subprocess import check_output
    
    lines = check_output("a | b", shell=True, universal_newlines=True).splitlines()
    

    这里是a workaround if your Python version has no check_output()。如果您想在进程仍在运行时一次读取一行,请参阅Python: read streaming input from subprocess.communicate()

    您可以尝试使用 osctypes 模块来获取信息,而不是 grepping 外部命令的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      相关资源
      最近更新 更多