【问题标题】:python subprocess not working. it is not replacing variable outputpython子进程不工作。它没有取代可变输出
【发布时间】:2018-10-13 07:45:11
【问题描述】:

我有以下用于检查 ping 状态的功能

def pingOk(sHost):
    try:
        output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)
    except Exception, e:
        traceback.print_exc()
        return False

    return True

我尝试运行脚本

 pingOk(sHost)

我遇到以下错误:

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
Traceback (most recent call last):
  File "set_enviroment.py", line 54, in pingOk
    output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)
  File "/usr/lib64/python2.7/subprocess.py", line 575, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
CalledProcessError: Command 'ping -c 1 ' returned non-zero exit status 2

看起来它没有格式化输出。请有人帮助我做错了什么

【问题讨论】:

  • 可能是由于使用 ping 命令的格式错误,因为它显示 ping 使用帮助我建议您之前打印命令并在终端中验证它。
  • 它工作正常,我测试过,它是格式化变量问题。如果我使用硬代码值,它可以正常工作
  • print("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost)) 并检查你得到了正确的命令
  • 看起来 IP 格式是空的,谢谢 Pavan

标签: python python-2.7 subprocess


【解决方案1】:

由于投诉是关于ping -c 1 ,而不是ping -{} 1 {},很明显.format确实发生了。

由于投诉是关于ping -c 1 (注意尾随空格),很明显.formatsecond 参数是一个空字符串。

命令失败的抱怨大概是因为ping 期望一个目的地(因此所有的标准错误都抱怨使用情况)。

【讨论】:

    猜你喜欢
    • 2016-11-19
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 2011-09-08
    相关资源
    最近更新 更多