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]

    奇怪。

Working with Django Model

  1. Sub-queries used for query pk dee in  main talbe

Create your models here.
class projects(models.Model):
    #env = models.ForeignKey(deploy_env, on_delete=models.CASCADE)
    project_name = models.CharField(max_length=200)
    create_date = models.DateTimeField(default=0)
    owner = models.CharField(max_length=200)

    def __str__(self):
        return self.project_name
class AppEnv(models.Model):

    name = models.CharField(max_length=200, unique=True)
    def __str__(self):
        return self.name

class MGDeployEnv(models.Model):
    deploy_env = models.OneToOneField(minion_groups, on_delete=models.CASCADE)
    project_name = models.ForeignKey(projects, on_delete=models.CASCADE)
    env_name = models.ForeignKey(AppEnv, on_delete=models.CASCADE)
    pillar = models.TextField()
    state = models.TextField()
    current_version = models.CharField(max_length=200, blank=True)
    status = models.CharField(max_length=200, blank=True)
    comments = models.CharField(max_length=200, blank=True)
    update_on = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return str(self.deploy_env)
class tasks(models.Model): #question = models.ForeignKey(Question, on_delete=models.CASCADE) #project_name = models.ForeignKey(projects, on_delete=models.CASCADE) env = models.ForeignKey(deploy_env, on_delete=models.CASCADE) deploy_url = models.CharField(max_length=200) owner = models.CharField(max_length=200) date = models.DateTimeField(default=timezone.now) status = models.CharField(max_length=200, blank=True) result = models.TextField(blank=True) def __str__(self): return self.deploy_url

1.1 Command line tests:

>> env_id=deploy_env.objects.filter(project_name_id=5)
>>> qt=tasks.objects.filter(env_id__in=env_id)
>>> qt.values()

<QuerySet [{‘deploy_url’: ‘testurl’, ‘id’: 11, ‘env_id’: 12, ….. etc

class tasks(models.Model):
    #question = models.ForeignKey(Question, on_delete=models.CASCADE)
    #project_name = models.ForeignKey(projects, on_delete=models.CASCADE)
    #env = models.ForeignKey(deploy_env, on_delete=models.CASCADE)
    env = models.ForeignKey(MGDeployEnv, on_delete=models.CASCADE)
    deploy_url = models.CharField(max_length=200)
    owner = models.CharField(max_length=200)
    date = models.DateTimeField(default=timezone.now)
    status = models.CharField(max_length=200, blank=True)
    result = models.TextField(blank=True)

    def __str__(self):
        return self.deploy_url

More Model Query:

There two methods to get the searching result, for example.

1.2 Foward query (query by main set)

if we would like get the all deploy environment of PROD,  or deploy environment of Projects test, we can do following query:

by project

pj=projects.objects.get(project_name=‘abc’)

pj.mgdeployenv_set.all()

or shorter 

projects.objects.get(project_name=‘cpg’).mgdeployenv_set.all()

<QuerySet [<MGDeployEnv: cpg_cons_be>, <MGDeployEnv: cpg_cons_all>]>

by environments

env = AppEnv.objects.get(name=’cons’)

env.mgdeployenv_set.all()

QuerySet [<MGDeployEnv: abc_cons_be>, <MGDeployEnv: abc_cons_all>]>

1.3 BackForward query(query by sub set)

by project

MGDeployEnv.objects.filter(project_name__in=projects.objects.filter(project_name=‘abc’))

<QuerySet [<MGDeployEnv: abc_cons_be>, <MGDeployEnv: abc_cons_all>]>

by environments

MGDeployEnv.objects.filter(env_name__in=AppEnv.objects.filter(name=‘cons’))

<QuerySet [<MGDeployEnv: abc_cons_be>, <MGDeployEnv: abc_cons_all>]>

 

as you can see, this 4 queries are the same.

 

Reference Links:

http://scottlobdell.me/2015/01/sql-database-best-practices-django-orm/ 

 

2. Many to Many

https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_many/

Regular Expression to minimum(non-greedy) matching

If we would like to match multiple duplicate content in the same line, we would like to use minimum match by using RE.

for example:

filename: text

pillar[‘abc’]
pillar[‘abc’]
pillar[‘abc’]}pillar[‘wx’]||pillar[‘yz’]
pillar[‘abc’]

1. matched expression python

import re

f=open('./text','r').read()
# non-greddy result:

print(re.findall('(pillar\[.*?\])',f))

# ourput: ["pillar['abc']", 
"pillar['abc']", 
"pillar['abc']", 
"pillar['wx']", 
"pillar['yz']", 
"pillar['abc']"]

# greedy match result:

print(re.findall('(pillar\[.*\])',f))

#output: ["pillar['abc']", 
"pillar['abc']", 
"pillar['abc']}pillar['wx']||pillar['yz']", 
"pillar['abc']"]

 

2. matched expression using shell

grep -o -P "pillar\['.*?'\]" text

# output: 
pillar['abc']
pillar['abc']
pillar['abc']
pillar['wx']
pillar['yz']
pillar['abc']

Set Proxy of env using python

Use http://www.someproxy.com:3128 for http proxying
proxies = {‘http’: ‘http://www.someproxy.com:3128’}
filehandle = urllib.urlopen(some_url, proxies=proxies)
# Don’t use any proxies
filehandle = urllib.urlopen(some_url, proxies={})
# Use proxies from environment – both versions are equivalent
filehandle = urllib.urlopen(some_url, proxies=None)
filehandle = urllib.urlopen(some_url)

喜欢这样的小程序 李少宏 python简明教程练习–命令行 地址簿 程序

reference link:
李少宏
python简明教程练习–命令行 地址簿 程序

在这个程序中,你可以添加、修改、删除和搜索你的联系人(朋友、家人和同事等等)以及它们的信息(诸如电子邮件地址和/或电话号码)。这些详细信息应该被保存下来以便以后提取。

由于上个程序中的代码没有把信息从文件中读取出来,我们可以把相同的信息保存在info.txt文件中去,这使得info.txt文件会有多余的东西。以下是我修改后的代码

代码:

”’

Created on 2011-10-16

@author: Descusr

”’

# coding:utf-8

import sys

import os

import cPickle

class Person:

filename = ‘info.txt’

def __init__(self, name, phone):

self.name = name

self.phone = phone

self.personlist = {self.name:self.phone}

def add(self):

self.name = raw_input(“Enter name:”)

if self.name in self.personlist.keys():

print “The name is exist!”

else:

self.phone=raw_input(“Enter phone:”)

self.personlist[self.name] = self.phone

print “Contact saved!”

def Modify(self):

self.name = raw_input(“Enter name:”)

if self.name in self.personlist.keys():

self.phone = raw_input(“Enter new phone:”)

self.personlist[self.name] = self.phone

print “Contact saved!”

else:

print “The name is not in here!!”

def delete(self):

self.name = raw_input(“Enter name:”)

if self.name in self.personlist.keys():

del self.personlist[self.name]

print “Deleted!!”

else:

print “The name is not in here!!”

def search(self):

self.name = raw_input(“Enter name:”)

if self.name in self.personlist.keys():

print ‘Name:%s,Phone:%s’%(self.name,self.phone)

else:

print “The name is not in here!!”

def save(self):

f = file(self.filename,’w’)

cPickle.dump(self.personlist,f)

f.close()

print “Your contacts list has been saved to file:%s successfully~” %self.filename

def load(self):

if os.path.exists(self.filename):

f = file(self.filename)

self.personlist = cPickle.load(f)

f.close()

def show(self):

for self.name,self.phone in self.personlist.items():

print “Name:%s Phone number:%s” %(self.name,self.phone)

if __name__ == ‘__main__’:

os.system(‘clear’)

command = [‘add’,’modify’,’search’,’delete’,’quit’ ,’show’]

person = Person(”,”)

person.load()

while True:

print “The contact person:”

str = raw_input(‘What are you going to do(add/modify/search/delete/show/quit)?’)

if str in command:

if str == ‘add’:

person.add()

elif str == ‘modify’:

person.Modify()

elif str == ‘search’:

person.search()

elif str == ‘delete’:

person.delete()

elif str == ‘show’:

person.show()

else:

ch = raw_input(“Your contacts list hasn’t been saved,save it now?(Y/N)”)

if ch == ‘y’:

person.save()

sys.exit()

else:

sys.exit()

print “Exit the System”

break

else:

print “Please input the command!”

Installing Python2.6.7 On CentOS5

Source Link: http://www.hostucan.com/webmaster-tutorials/centos-python-2.6-install
Install Python 2.6 on CentOS 5

CentOS 5 is the most common Python hosting environment in the market, but the default version of python it is 2.4 now. As some projects request the python version to be greater than V2.5, in this article, you will see how to install python 2.6 by compiling source code step by step.

1. Download python source from python.org and Uncompress it.

$ wget http://www.python.org/ftp/python/2.6.7/Python-2.6.7.tgz
$ tar xzvf Python-2.6.7.tgz
2. Build & Install. In the source code folder:
$ ./configure –prefix=/opt/python2.6 –with-threads –enable-shared –with-zlib=/usr/include
$ make
$ make install
3. Add Python 2.6 lib to system lib. execute:
$ sudo ln -s /opt/python2.6/lib/libpython2.6.so /usr/lib
$ sudo ln -s /opt/python2.6/lib/libpython2.6.so.1.0 /usr/lib

# Create necessary links and cache
$ sudo /sbin/ldconfig -v

# make a symbolic link to python
$ sudo ln -s /opt/python2.6/bin/python /usr/local/python
4. Check python version use “python -V”. If you still see old version of Python, you need to edit /etc/profile (as root), add the following line:
pathmunge /opt/python2.6/bin/
Above setting should be added before the line like:
export PATH USER LOGNAME MAIL HOSTNAME HISTSIZE INPUTRC
Then re-login system, try “python -V” again. 5. After install yum, try “yum search php” This is to make sure we did not accidentally mess up “yum”, which is the biggest threat when upgrading Python version. If you see no errors, you should be good to start using Python 2.6.

Update python-MySQLdb

http://blog.csdn.net/inte_sleeper/article/details/6556103

Python sys.path…

转:
python sys模块包含了与python解释器和它的环境有关的函数,这个你可以通过dir(sys)来查看他里面的方法和成员属性

里面有个 sys.path属性。他是一个list.默然情况下python导入文件或者模块的话,他会先在sys.path里找模块的路径。如果没有的话,

程序就会报错。

所以我们一般自己写程序的话。最好把自己的模块路径给加到当前模块扫描的路径里,eg: sys.path.append(‘你的模块的名称’),这样程序就不会

因为找不到模块而报错。。

我感觉python sys.path和python __init__.py 这2个东西开始学的时候比较容易出问题。所以要注意下。

如果对这个兴趣,可以看看相关的: [python path] [python os.system]

Python-OptParser Global args operations.


def setup_cmdline_parser():
    parser = _o.OptionParser()
    parser.add_option("-l", "--live", dest="live", action="store_true",
                      default=True, help = "show the ncurses live monitoring frontend (default)")
    parser.add_option("-n", "--notlive", dest="live", action="store_false",
                      default="True", help = "write to file instead of live monitoring")
    parser.add_option("-p", "--prefix", dest="prefix",
                      default = "log", help="prefix to use for output files")
    parser.add_option("-t", "--time", dest="duration", action="store", type="int", default=10,
            help="stop logging to file after this much time has elapsed (in seconds). set to 0 to keep logging indefinitely")
    return parser


def main():
    global options
    global args
    global domains

    parser = setup_cmdline_parser()
    (options, args) = parser.parse_args()

    if len(args):
        parser.error("No parameter required")
    if options.mspersample < 0:
        parser.error("option --ms_per_sample: invalid negative value: '%d'" %
                     options.mspersample)
    # If --ms_per_sample= is too large, no data may be logged.
    if not options.live and options.duration != 0 and \
       options.mspersample > options.duration * 1000:
        parser.error("option --ms_per_sample: too large (> %d ms)" %
                     (options.duration * 1000))

    start_xenbaked()
    if options.live:
        show_livestats(options.cpu)
    else:
        try:
            writelog()
        except:
            print 'Quitting.'
    stop_xenbaked()

Using options, args out of functions with “global”