我的代码问题是,它另外弹出一个控制台,我想把这个黑框去掉,另一方面是不管是否ping通都返回true
2 回答

阿晨1998
TA贡献2037条经验 获得超6个赞
你这样直接使用os.system("ping")==0是不行的,执行ping命令后跟cmd执行一样,也会返回类似于ttl=245 time=36.798 ms这样的信息。所以你要做的是:
在os.system("ping -n 1 "+ip)的返回结果中查找是否存在"TTL="这样的字符,如果存在表示ping通了,不存在就表示超时

拉莫斯之舞
TA贡献1820条经验 获得超10个赞
def ping(host): '''ping 1次指定地址''' import subprocess,traceback, platform if platform.system() = = 'Windows' : cmd = 'ping -n %d %s' % ( 1 ,host) else : cmd = 'ping -c %d %s' % ( 1 ,host) try : p = subprocess.Popen(args = cmd, shell = True , stdout = subprocess.PIPE, stderr = subprocess.STDOUT) (stdoutput,erroutput) = p.communicate() # print stdoutput except Exception, e: traceback.print_exc() if platform.system() = = 'Windows' : return stdoutput.find( 'Received = 1' )> = 0 else : return stdoutput.find( '1 packets received' )> = 0 if __name__ = = "__main__" : print ping( 'baidu.com' ) |
添加回答
举报
0/150
提交
取消