偶尔用Python做点事情,用的时候隔了许久,又不太记得了,有时连基本的语法都忘掉,这里记录在一张纸上,方便查看。也涵盖比较实用的内容,方便信手捻来(我没写错吧)
其中代码片段主要摘自前段时间写的一些Python代码。
- Python Help
>>> python(“subprocess”)
帮助是很重要,linux程序员,你懂的
- Python tutorial
https://docs.python.org/2/tutorial/
初学Python的人用这个好,计算机领域,不懂的google tutorial,你也懂的
- 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 arrival deque([‘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 ET def 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