【问题标题】:Getting error while executing ping through subprocess.call()通过 subprocess.call() 执行 ping 时出错
【发布时间】:2014-04-05 07:41:38
【问题描述】:

我给了

subprocess.call(['ping', '127.0.0.1', '>>', 'out15.txt'])

python 脚本中的语句。

但我收到未知主机错误。

请告诉我为什么会出现这个错误。

【问题讨论】:

  • localhost 工作了吗?错误是什么?
  • 是的 localhost 正在工作。错误是“ping 未知主机”@Arvind
  • 您似乎期待 shell 解释。这不是ping 知道该怎么做的事情;那是bash 或您使用的任何外壳。有一个 shell 参数可以通过 shell 传递命令,但它是一个拐杖。以其他方式获得效果更安全。

标签: python subprocess ping


【解决方案1】:

因为您将 >> out15.txt 作为参数传递给 ping。 >> 是 cmd\bash 的特殊字符。如果您坚持使用命令将输出重定向到文件,而不是使用 python 代码,您可以这样做:

subprocess.call(['cmd', '/c', 'ping', '127.0.0.1', '>>', 'out15.txt'])

对于 bash 也是如此。

【讨论】:

  • 你能解释一下为什么你在 subprocess.call() @Ori Seri 中给出了 cmd ,/c
  • 正如我所说,'>>' 是 cmd 的一个特殊字符。 Ping 不知道这个标志,它将它作为您要 ping 的主机的一部分,并尝试解决它。所以,我打开了 cmd 进程而不是 ping 进程。 /c 参数告诉 cmd 运行以下命令并退出(在我们的例子中 - ping)。 Cmd 将“>>”称为重定向,因此将 ping 的标准输出重定向到文件。注意:cmd进程负责重定向输出,而不是ping进程。
  • 我收到错误 OSError(Errno 2): No such file or directory when I have given subprocess.call() 如上所述-@Ori Seri
  • 你的意思是:call(['cmd', '/c', "ping 127.0.0.1 >> out15.txt"])(或call('ping 127.0.0.1 >> out15.txt', shell=True))?
【解决方案2】:

由于@Ori Seri pointed out >> 通常由shell解释:

from subprocess import call

call('ping 127.0.0.1 >> out15.txt', shell=True)

注意:字符串参数为shell=True

你可以在没有外壳的情况下做到这一点:

with open('out15.txt', 'ab', 0) as output_file:
    call(["ping", "127.0.0.1"], stdout=output_file)

注意:列表参数带有shell=False(默认)。

您不需要编写输出文件来解释ping 结果;您可以改用退出状态:

from subprocess import call, DEVNULL

ip = "127.0.0.1"
rc = call(["ping", '-c', '3', ip], stdout=DEVNULL)
if rc == 0:
    print('%s active' % ip)
elif rc == 2:
    print('%s no response' % ip)
else:
    print('%s error' % ip)

Multiple ping script in Python

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    相关资源
    最近更新 更多