我的代碼問題是,它另外彈出一個控制臺,我想把這個黑框去掉,另一方面是不管是否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
提交
取消