python3.x入手,修改了2.x的代码兼容3.x

来源:互联网 发布:淘宝信用卡怎么办理 编辑:程序博客网 时间:2024/05/07 19:54

    搜索python教程,好几次都看到一个关于对比java和python代码的简洁性。作为java出身的我,自然就想敲一下看看python到底好在哪里。

    可惜呢。按照文章介绍,敲出来的代码运行的时候报错。o(╯□╰)o

    看了一下,python3.x 的print方法为 print(); 而不是print “ ”; 了。略囧

    其次,3.x对str的处理也不一样了,3.x执行的是byte,不同于2.x的ascii,所以对str到字节流的时候要encode一下,输出流要decode一下。

   代码变为这样:

strstring='ping 121.250.218.'+str(begin)+'\n'p.stdin.write(strstring.encode())
print("exe result:"+p.stdout.read().decode("gbk"))  

 对,顺便提醒:cmd的输出要用gbk解码而不是utf8解码。

如果不加解码的话就会变为 /x01-/xff 这样的字节流了~

附上完整代码:

import subprocesscmd="cmd.exe"begin=240end=255while begin<end:    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,                       stdin=subprocess.PIPE,stderr=subprocess.PIPE)    strstring='ping 121.250.218.'+str(begin)+'\n'    begin=begin+1    p.stdin.write(strstring.encode())    p.stdin.close()    p.wait()    print("exe result:"+p.stdout.read().decode("gbk"))    


0 0
原创粉丝点击