Python 2.7 Python脚本中的ping请求失败

Python 2.7 Python脚本中的ping请求失败,python-2.7,ping,Python 2.7,Ping,我有一个python脚本,希望ping几个(相当多!)主机。我已经将其设置为读取hosts.txt文件的内容,作为脚本中ping的主机。奇怪的是,对于前几个地址(无论它们是什么),我收到了以下错误: 我已经两次(在文件中)包含了上面显示的地址,并且它尝试ping。任何关于我做错了什么的想法-我是一个python新手,所以要温柔 这是我的剧本: 导入子流程 hosts\u file=open(“hosts.txt”、“r”) lines=hosts\u file.readlines() 对于行中

我有一个python脚本,希望ping几个(相当多!)主机。我已经将其设置为读取hosts.txt文件的内容,作为脚本中ping的主机。奇怪的是,对于前几个地址(无论它们是什么),我收到了以下错误:

我已经两次(在文件中)包含了上面显示的地址,并且它尝试ping。任何关于我做错了什么的想法-我是一个python新手,所以要温柔


这是我的剧本:

导入子流程
hosts\u file=open(“hosts.txt”、“r”)
lines=hosts\u file.readlines()
对于行中的行:
ping=子进程.Popen(
[“ping”、“-n”、“1”行],
stdout=子流程.PIPE,
stderr=子流程.PIPE
)
输出,错误=ping.communicate()
打印出来
打印错误
hosts_file.close()
这是我的hosts.txt文件:

66.211.181.182
178.236.5.39
173.194.67.94
66.211.181.182
以下是上述测试的结果:

Ping request could not find host 66.211.181.182
. Please check the name and try again.


Ping request could not find host 178.236.5.39
. Please check the name and try again.


Ping request could not find host 173.194.67.94
. Please check the name and try again.



Pinging 66.211.181.182 with 32 bytes of data:
Request timed out.

Ping statistics for 66.211.181.182:
    Packets: Sent = 1, Received = 0, Lost = 1 (100% loss)

看起来
变量的末尾包含换行符(文件的最后一行除外)。从:

f.readline()
从文件中读取一行;换行符(
\n
)保留在字符串的末尾,仅当文件未以换行符结尾时,才会在文件的最后一行忽略

在调用
Popen

之前,您需要去除
\n
,并提供一些注释:

  • 强烈建议不要使用readlines(),因为它会将整个文件加载到内存中
  • 我建议使用Generator在每条线路上执行rstrip,然后ping服务器
  • 无需使用file.close-您可以使用with语句为您执行此操作
  • 您的代码应该如下所示:

    import subprocess
    def PingHostName(hostname):
        ping=subprocess.Popen(["ping","-n","1",hostname],stdout=subprocess.PIPE
                      ,stderr=subprocess.PIPE)
        out,err=ping.communicate();
        print out
        if err is not None: print err
    
    with open('C:\\myfile.txt') as f:
        striped_lines=(line.rstrip() for line in f)
        for x in striped_lines: PingHostName(x)  
    

    @EliAcherkan,我想这是有道理的。。。当我测试这个阅读部分时,我只是简单地打印了行,它打断了行。我该怎么克服呢?这就是问题所在!!!-我添加了“line=line.strip()”来去除两边的所有空白,而不仅仅是一条新线。谢谢你的帮助:)谢谢你的反馈。。。几个问题。。。什么是发电机。。。你用过它吗?生成器是用惰性计算动态生成的对象。当您使用生成器浏览列表时,实际上并不创建列表并对其进行迭代,而是动态创建列表中的每一项。您可以在中阅读更多关于它们的信息,是的,我在这里使用生成器(f行的line.rstrip()返回生成器对象感谢您的响应。。。我在过多的帖子中看到过发电机,但我并不真正理解我读到的描述。。你提供的这个很有帮助。我将试用这段代码,看看周末如何使用over生成器。谢谢,我会支持你的答案,但是没有足够的声誉(或者不管它叫什么),好的:)你可以接受这个答案。希望能有所帮助
    import subprocess
    def PingHostName(hostname):
        ping=subprocess.Popen(["ping","-n","1",hostname],stdout=subprocess.PIPE
                      ,stderr=subprocess.PIPE)
        out,err=ping.communicate();
        print out
        if err is not None: print err
    
    with open('C:\\myfile.txt') as f:
        striped_lines=(line.rstrip() for line in f)
        for x in striped_lines: PingHostName(x)