python subprocess.call参数问题

时间:2016-05-22 05:40:02

标签: python linux subprocess call

我正在Linux下编写一个简单的python脚本,使用subprocess对我子网中的主机进行一批并发单行ping。

手动命令有效: ping -c 1 192.168.68.1

脚本::

#!/usr/bin/python
from subprocess import call

path = "ping"
flags = "-c 1 "

for i in range(1,3):
    ip_addr = "192.168.68." + str(i)
    args = flags + ip_addr

    print "doing: {} {}".format(path, args)        
    call([path, args])

评论出预期的电话输出:

doing: ping -c 1 192.168.68.1
doing: ping -c 1 192.168.68.2

使用call(),脚本似乎调用ping但参数未知。输出如下:

doing: ping -c 1 192.168.68.1
Usage: ping [-aAbBdDfhLnOqrRUvV64] [-c count] [-i interval] [-I interface]
        [-m mark] [-M pmtudisc_option] [-l preload] [-p pattern] [-Q tos]
        [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp_option]
        [-w deadline] [-W timeout] [hop1 ...] destination
Usage: ping -6 [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface]
         [-l preload] [-m mark] [-M pmtudisc_option]
         [-N nodeinfo_option] [-p pattern] [-Q tclass] [-s packetsize]
         [-S sndbuf] [-t ttl] [-T timestamp_option] [-w deadline]
         [-W timeout] destination
doing: ping -c 1 192.168.68.2
Usage: ping [-aAbBdDfhLnOqrRUvV64] [-c count] [-i interval] [-I interface]
        [-m mark] [-M pmtudisc_option] [-l preload] [-p pattern] [-Q tos]
        [-s packetsize] [-S sndbuf] [-t ttl] [-T timestamp_option]
        [-w deadline] [-W timeout] [hop1 ...] destination
Usage: ping -6 [-aAbBdDfhLnOqrRUvV] [-c count] [-i interval] [-I interface]
         [-l preload] [-m mark] [-M pmtudisc_option]
         [-N nodeinfo_option] [-p pattern] [-Q tclass] [-s packetsize]
         [-S sndbuf] [-t ttl] [-T timestamp_option] [-w deadline]
         [-W timeout] destination

对于每次迭代,似乎ping被调用两次,其中args与我期望的不同。我注意到ping -6论证抱怨。
我将不胜感激,尤其是在正确使用call()方面。

更新
添加了bash脚本我试图模仿:

#!/bin/bash
for ip in $(seq 1 2); do
    ping -c 1 192.168.68.$ip &
done

2 个答案:

答案 0 :(得分:2)

传递给函数call的参数应该是列表中的单个元素,如下所示:

call(['ping','-c','1','192.168.68.2'])

我无法重现'双重打印'在我的环境中。

答案 1 :(得分:0)

由于@Pablo提到flagspath变量应该是一个列表元素,所以在调用call方法之前只需将命令字符串转换为list:

path = "ping"
flags = "-c 1"
cmd_list = [path] # convert string to list
cmd_list = cmd_list + flags.split(' ') # converting your flags string to list elements

call(cmd_list)