Discuss / Python / subprocess.Popen 获取结果问题

subprocess.Popen 获取结果问题

雷培钊

#1 Created at ... [Delete] [Delete and Lock User]
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import time

def pingtest():
    cmd="cmd.exe"
    ips=""
    begin=1
    end=5
    print(u"--------正在测试中请等待--------")
    fd=open("test.txt","w")
    while begin<end:
        p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)
        p.stdin.write("ping 192.168.1."+str(begin)+"\n")
        #p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)
        p.stdin.close()
        p.wait()
        out = p.stdout.read()
        fd.write(out);
        print "execution result: %s-------"%out.decode("GBK")
        if u"请求超时" in out.decode("GBK"):
             print "192.168.1."+str(begin)+u":连接异常"
        else:
             print "192.168.1."+str(begin)+u":连接正常"
        begin=begin+1
    fd.close()
    raw_input("Press Enter to continue: ")


if __name__=="__main__":
    pingtest()

代码f5运行效果 在out 中能够查询到“请求超时”字符串,但用py2exe打包以后运行,查询不到“请求超时”的字符串了, 把内容记录到记事本中发现,p.stdout.read()获取不到返回的内容了?

雷培钊

#2 Created at ... [Delete] [Delete and Lock User]

f5运行结果

C:\Python27>ping 192.168.1.4

正在 Ping 192.168.1.4 具有 32 字节的数据:

请求超时。

请求超时。

请求超时。

请求超时。

192.168.1.4 的 Ping 统计信息:

数据包: 已发送 = 4,已接收 = 0,丢失 = 4 (100% 丢失),

C:\Python27>------- 192.168.1.4:连接异常

打包后运行结果 : C:\Python27\dist>ping 192.168.1.3

C:\Python27\dist>Microsoft Windows [版本 6.1.7601]

版权所有 (c) 2009 Microsoft Corporation。保留所有权利。

C:\Python27\dist>ping 192.168.1.4

用ret,out=subprocess.check_output(cmd,.....),可以直接得到命令运行后的结果


  • 1

Reply