Python 非常奇怪的代码现象

  1. #!/usr/bin/python
    
    
    import os
    from subprocess import *
    import sys
    
    import yaml
    def local_run(cmd):
        if cmd:
            p = Popen(cmd, shell=True, stdout=PIPE,stderr=PIPE)
            out,err = p.communicate()
        return(p.returncode, out, err)
    
    
    if __name__ == '__main__':
        rst = local_run("salt 'dev*' state.apply test  --out=yaml")
        data=yaml.load(rst[1])
        if rst[0] == 0:
            print([ data[k][cmd]['result'] for cmd in data[k].keys() for k in data.keys() ])
            print([ [data[k][cmd]['result'] for cmd in data[k].keys() ] for k in data.keys() ])
            # method 1
            #for k in data.keys():
            #    for cmd in data[k].keys():
            #        print data[k][cmd]['result']
            # method 2
        else:
            print rst[2]
            [ data[k][cmd]['result'] for cmd in data[k].keys() for k in data.keys() ]
            sys.exit(rst[0])
    
    

    Traceback (most recent call last):

      File “test.py”, line 20, in <module>

        print([ data[k][cmd][‘result’] for cmd in data[k].keys() for k in data.keys() ])

    NameError: name ‘k’ is not defined

    2. 将两个Expression 对掉,却能生效

    #!/usr/bin/python
    
    
    import os
    from subprocess import *
    import sys
    
    import yaml
    def local_run(cmd):
        if cmd:
            p = Popen(cmd, shell=True, stdout=PIPE,stderr=PIPE)
            out,err = p.communicate()
        return(p.returncode, out, err)
    
    
    if __name__ == '__main__':
        rst = local_run("salt 'dev*' state.apply test  --out=yaml")
        data=yaml.load(rst[1])
        if rst[0] == 0:
            print([ [data[k][cmd]['result'] for cmd in data[k].keys() ] for k in data.keys() ])
            print([ data[k][cmd]['result'] for cmd in data[k].keys() for k in data.keys() ])
            # method 1
            #for k in data.keys():
            #    for cmd in data[k].keys():
            #        print data[k][cmd]['result']
            # method 2
        else:
            print rst[2]
            [ data[k][cmd]['result'] for cmd in data[k].keys() for k in data.keys() ]
            sys.exit(rst[0])

    [[True], [True]]

    [True, True]

    奇怪。

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay

Leave a Reply

Your email address will not be published. Required fields are marked *