【问题标题】:IP address must be specified?必须指定 IP 地址?
【发布时间】:2018-01-22 11:27:44
【问题描述】:

这是我在 windows 10 上的 python 2.7 中运行的代码

import os

with open('test.txt') as f:
    for line in f:
         response = os.system("ping -c 1" + line)
         if response == 0:
                 print(line, "is up!")
         else:
                 print(line, "is down!")

test.txt 文件包含一些随机 IP,代码会运行,但当它运行时会发出消息,必须指定 IP 地址。我的问题是我不知道如何在脚本中做到这一点。当我使用常规命令 promt 并执行 ping -c 1 google.com 时,它会运行,但使用上述 python 脚本从文本文件中读取它,需要指定相同的 google.com。

Q1:指定 ip 是什么意思,我该怎么做?

Q2:我应该以不同的方式编写代码来导入不同的模块吗?

【问题讨论】:

  • 查看for 循环中的缩进。 (提示:没有:))。条件 if 语句也是如此。
  • ~~首先,你试过让它打印出“line”的内容吗?你会更好地了解故障在哪里。~~(假装它被击穿)是的,这样做^
  • 是的,我试过只打印线条,它会单独给出它们之间的一些空间。我还修复了这里的缩进,我的代码中有它,只是这里没有。
  • 如果文件中的一行包含google.com,则您尝试执行的结果命令是ping -c 1google.com。请注意,与您的手动命令相比,缺少空格 - 该地址被解释为 -c 选项的参数的一部分。

标签: python python-2.7 ip-address ping


【解决方案1】:
import os

with open('test.txt') as f:

 for line in f:

  response = os.system("ping -c 1 " + line.strip())

  if response == 0:

   print(line, "is up!")

  else:

   print(line, "is down!")

从文件中删除记录末尾的换行符并在 ping 命令中添加一个空格。

【讨论】:

  • 啊,看看我的代码的所有迭代,我发现我开始打字时没有空格,非常感谢。
猜你喜欢
  • 2019-08-25
  • 1970-01-01
  • 2017-07-06
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多