python basic note

來源:互聯網
上載者:User

標籤:python

偶爾用Python做點事情,用的時候隔了許久,又不太記得了,有時連基本的文法都忘掉,這裡記錄在一張紙上,方便查看。也涵蓋比較實用的內容,方便信手撚來(我沒寫錯吧650) this.width=650;" src="http://img.baidu.com/hi/jx2/j_0059.gif" alt="j_0059.gif" />)

其中程式碼片段主要摘自前段時間寫的一些Python代碼。

  • Python Help

>>> python(“subprocess”)

協助是很重要,linux程式員,你懂的

  • Python tutorial

https://docs.python.org/2/tutorial/

初學Python的人用這個好,電腦領域,不懂的google tutorial,你也懂的650) this.width=650;" src="http://img.baidu.com/hi/jx2/j_0028.gif" alt="j_0028.gif" />

  • Framework

1. Inherit, 要寫大點的東西,物件導向不能少

import subprocess  class VirtualCommand():         def __init__(self):                 self._cmdstr = None                 pass          def cmdstr(self):                 return self._cmdstr          def execute(self):                 return True  class Command(VirtualCommand):         def __init__(self, cmdstr="echo hello"): # default value to cmdstr                 VirtualCommand.__init__(self)    # call init of parent                 self._cmdstr = cmdstr.strip()          # called by Task methods, and can be inheritted         def execute(self, stdin=None):                 cmd = self._cmdstr.split(" ")                 p = subprocess.Popen(cmd, stdin=stdin)                 p.wait()                 return True  if __name__ == "__main__":      #main entry         cmd = Command("ls")         cmd.execute()


2. Input and flow control basic,有時連這些都不記得了

if __name__ == "__main__":      #main entry         x = int(raw_input("Please enter an integer: "))         if x < 0:                 print "Negative"         elif x == 0:                 print "Zero"         else:                    print "More"                          str = "this is a line"         for word in str.split():                 print word          for i in range(10):                 print i          i = 0         while i < 10:                 print i                 i += 1

3. file operation, string to int, 2d array usage

if __name__ == "__main__":         m = [[0 for x in range(6)] for x in range(8)]  # initialization of 2d array        with open("aa") as f:                 content = f.readlines()         i = 0         for line in content:                 la = line.split(",")                 m[cnt][0] = int(la[0])  #received                 m[cnt][1] = int(la[1])  #injected         ... ...                cnt += 1

 
4. input parameters, signal, dictionary
 

import sys import signal import time  class Generator:     mod_name = ‘generator‘     running = True          help = """Usage: snorttf.py [parameter=value] Parameters:     hs        http speed(default is 1000)     ds        dns speed(default is 10)     ss        smtp speed(default is 10)     server        smtp server     """      args = {         ‘hs‘ : ‘1000‘,         ‘ds‘  : ‘10‘,              ‘ss‘ : ‘10‘,                "server" : "test11"         }      def __init__(self, args):         self.get_input_param(args)                        def get_input_param(self, input_args):         arg_num = len(input_args)         for i in range(1, arg_num):             arg = input_args[i]             elms = arg.split(‘=‘)             if elms[0] == ‘help‘:                 print self.help                 sys.exit(0) #            print elms             if elms[0] in self.args and len(elms) == 2:                 self.args[elms[0]] = elms[1]             else:                 print ‘input wrong argument:‘, arg                 print self.help                 sys.exit(0)                                   def check_parameters(self):         self.httpspeed = int(self.args[‘hs‘])         self.dnsspeed = int(self.args[‘ds‘])         self.smtpspeed = int(self.args[‘ss‘])         self.mailserver = self.args[‘server‘]         pass      def run_client(self):         self.check_parameters()         print "hs: " + str(self.httpspeed) + " ds: " + str(self.dnsspeed) + \                 " ss: " + str(self.smtpspeed) + " server: " + self.mailserver         #TODO         while self.running:             #TODO             time.sleep(1)         print "exit"  if __name__ == "__main__":         def signal_handler(signal, frame):             Generator.running = False          signal.signal(signal.SIGINT, signal_handler)         g = Generator(sys.argv)         g.run_client()

 

  • Basic

1. List
# 2d list, method len(), append()

>>> q = [2, 3]>>> p = [1, q, 4]>>> len(p)3>>> p[1][2, 3]>>> p[1][0]2>>> p[1].append(‘xtra‘)     # See section 5.1>>> p[1, [2, 3, ‘xtra‘], 4]# method sort()>>> a = [66.25, 333, 333, 1, 1234.5]>>> a.sort()>>> a[1, 66.25, 333, 333, 1234.5]

# As stack

>>> stack = [3, 4, 5]>>> stack.append(6)>>> stack.append(7)>>> stack[3, 4, 5, 6, 7]>>> stack.pop()7

#As Queue
#from collections import deque

>>> queue = deque(["Eric", "John", "Michael"])>>> queue.append("Terry")           # Terry arrives>>> queue.append("Graham")          # Graham arrives>>> queue.popleft()                 # The first to arrive now leaves‘Eric‘>>> queue.popleft()                 # The second to arrive now leaves‘John‘>>> queue                           # Remaining queue in order of arrivaldeque([‘Michael‘, ‘Terry‘, ‘Graham‘])

2. ssh through paramiko

    ssh = paramiko.SSHClient()     ssh.load_system_host_keys()     ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #WarningPolicy)     ssh.connect(host, port, username, password)    ssh.exec_command(self._cmdstr)

3. thread

    thread.start_new_thread(print_log, ("out", self._aout))

4. xml process

import xml.etree.ElementTree as ETdef get_config_env(path):     tree = ET.parse(path)     root = tree.getroot()     for child in root:         print child.tag, child.attrib, child.text

5. exception
Here try to execute task, if get any execption, perform term() to terminate any resources

    try:         task.execute()     except:         task.term()         raise

Here show an example of throw execption,

    try:        raise NameError(‘HiThere‘)    except NameError:        print ‘An exception flew by!‘        raise


  • Skills

1. When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing -i before the script.

2. installation
yum install python-setuptools  # this install easy_install
easy_install paramiko    # this install any modules

本文出自 “Summit” 部落格,請務必保留此出處http://jiangjqian.blog.51cto.com/1040847/1665946

python basic note

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.