Python 3版本较之前版本语法的一些

发布时间:2019-09-23 17:04:04编辑:auto阅读(1820)

    市面上的Python教程基本都是以3.0以下版本来讲解的,python 从3.0之后一些语法都做了写更改,有时候可能会浪费比较多的时间,记录下使用过程中遇到的情况以备后查。

    1、Print (1)需要加括号 (2)打印文件重定向

    (1)print ('hello world!!')

    (2) print([object, ...], *, sep=' ', end='\n', file=sys.stdout)

    1. log = open('test.txt','a')  
    2. print (1,2,3, file=log, end='\n')  
    3. print (4,5,6, file=log, end='\n')  
    4. log.close()  
    5. print (7,8,9

     2、commands modle 在3.0之后使用subprocess来代替。

    Deprecated since version 2.6: The commands module has been removed in Python 3.0. Use the subprocess module instead.

    1. >>> import commands  
    2. >>> commands.getstatusoutput('ls /bin/ls')  
    3. (0'/bin/ls')  
    4. >>> commands.getstatusoutput('cat /bin/junk')  
    5. (256'cat: /bin/junk: No such file or directory')  
    6. >>> commands.getstatusoutput('/bin/junk')  
    7. (256'sh: /bin/junk: not found')  
    8. >>> commands.getoutput('ls /bin/ls')  
    9. '/bin/ls' 
    10. >>> commands.getstatus('/bin/ls')  
    11. '-rwxr-xr-x  1 root        13352 Oct 14  1994 /bin/ls' 
    1. >>> import subprocess  
    2. >>> subprocess.getstatusoutput('ls /bin/ls')  
    3. (0'/bin/ls')  
    4. >>> subprocess.getstatusoutput('cat /bin/junk')  
    5. (256'cat: /bin/junk: No such file or directory')  
    6. >>> subprocess.getstatusoutput('/bin/junk')  
    7. (256'sh: /bin/junk: not found')  
    8. >>> subprocess.getoutput('ls /bin/ls')  
    9. '/bin/ls' 

     3. input 替代raw_input

    raw_input
    Converts raw_input() to input().

    1. while True:  
    2.     reply = input('Enter Text:')  
    3.     if reply == 'stop'break 
    4.     print (reply.upper()) 

     

     

关键字