Python Basic Note

Source: Internet
Author: User

Occasionally do something with Python, with a long time, and do not remember, and sometimes even the basic grammar are forgotten, here recorded in a piece of paper, convenient to view. Also covers more practical content, easy to twist (I did not write wrong bar 650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0059.gif "alt=" J_0059.gif "/>"

The code snippet is mainly excerpted from some Python code written in the previous period.

    • Python Help

>>> python ("subprocess")

Help is important, Linux programmers, you know.

    • Python Tutorial

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

Beginner python people with this good, computer field, do not understand Google tutorial, you also know 650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0028.gif "alt = "J_0028.gif"/>

    • Framework

1. Inherit, to write bigger things, object-oriented can not be less

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 &Nbsp;               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, which sometimes doesn't even remember.

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 (Ten):                  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                &nBsp;  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 '  :   '    &nbs ',p;      ' ds '   :  ',                ' ss '  :  ',                  "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]  &nBsp;          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__ ":    &Nbsp;     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>>& Gt 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 CH ILD 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's sometimes useful to being able to run the script and enter interactive mode afterwards. This can is done by passing-i before the script.

2. Installation
Yum Install Python-setuptools # this install Easy_install
Easy_install Paramiko # This install any modules

This article is from the "Summit" blog, make sure to keep this source http://jiangjqian.blog.51cto.com/1040847/1665946

Python Basic Note

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.