Python errors and exceptions, re-modules, multi-threading, Paramiko modules

Source: Internet
Author: User

File operations
X=open ('/etc/hosts ') # # #默认读的方式打开
X.readline ()
X.read ()
X.seek (0)
Y=open ('/root/new.txt ', ' W ')
Y.writelines (' abcd\n ')
Y.flush () Save
Y.close ()

Function
def function name (x,y=11):
Command

Function name (' Tom ', ' Jerry ')

Nameerrot Error not declared
Indexerror No Index
SyntaxError syntax error
Keyboardinterrupt user presses CTRL + C (interrupt) error
Eoferror ctrl+d Error
Ioerrot Input/output operation failed
Zerodivisionerror integer divisible error (such as 3/0 error)
ValueError value error (such as String is not an integer)
###############################
Set error # #可以把多个excep语句连接在一起 to handle multiple exceptions that may occur in a try block
#!/usr/bin/python
#coding: Utf-8
Try
Raw_input (' Please enter user name: ')
Except Keyboardinterrupt: # #如果上面结果出现异常KeyboardInterrupt (CTRL + C) Error print CTRL + C
print ' \ n You pressed CTRL + C '
Except Eoferror: # #如果上面结果出现异常EOFError错误 Print Ctrl+d
print ' \ n you pressed Ctrl+d '.
Except: # #如果上面结果出现其他异常错误 Print you made a mistake.
print ' Went wrong '
#################################
Number error
#!/usr/bin/python
#coding: Utf-8
Try
X=int (raw_input (' Please enter Number: '))
Print 3/x
Except Zerodivisionerror:
print ' cannot enter 0 '
Except ValueError:
print ' You're not typing a number '
#################################
Assigning the wrong content to a variable
#!/usr/bin/python
#coding: Utf-8
Try
X=int (raw_input (' Please enter Number: '))
Print 3/x
Except Zerodivisionerror,e:
print ' You're wrong ', E
Except ValueError:
print ' You're not typing a number '

###################################
#!/usr/bin/python
#coding: Utf-8
Try
X=int (raw_input (' Enter Number: ') # #输入字符串, convert to an integer, and assign to X
Print 3/x
Except Zerodivisionerror,e:
print ' You're wrong ', E
Except ValueError:
print ' You're not typing a number '
Else
print ' No problem ' # #不出错执行
Finally
print ' Game over ' # #出不出错都执行
#######################################
Determine if the file is closed

>> x=open ('/etc/hosts ')
>> x.closed # #文件关闭了吗
False
>> x.close () # #关闭文件
>> x.closed
True
##################################
>> with open ('/etc/hosts ') as x: # #将打开的文件操作放在with语句中的x内, code ending without indentation, file automatically closed
... x.readline () # #读一行包含结束符号 \ n
... x.readline () # #读一行包含结束符号 \ n
... # #没有缩进代表结束
' 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4\n ' # #文件第一行
':: 1 localhost localhost.localdomain localhost6 localhost6.localdomain6\n ' # #文件第二行
>> x.closed # #文件关闭了吗
True # #关闭

#################################
The result of a conditional judgment command
#!/usr/bin/python
#coding: Utf-8
X=int (raw_input (' Please enter 1-100 number: '))
Try
If x>100:
Raise ValueError, ' value cannot be greater than ' # ' #把x的结果触发为异常ValueError
If x<1:
Raise ValueError, ' value cannot be less than 1 '
Except Valueerror,e: # #如果异常出现ValueError, give the content to E
Print E # #打印错误显示的内容

########################################
Re module
################################

>> Import re
Re.match regular matches, matches only the beginning ^
>> x=re.match (' Hello ', ' hello the World ')
>> X.group ()
' Hello '

>> Import re
Re.search matches, matches all positions, matches only the first
X=re.search (' The ', ' Hello the Wod,,he app ')
>> X.group ()
' The '

>> Import re
Re.findall regular match, match all positions, all content
>> X=re.findall (' The ', ' Hello the Wod,,the app ')
>> x
[' The ', ' the ']

>> Import re
>> m=re.finditer (' foo ', ' Seafood ' food ')
>> for item in M:
... print item.group ()
...
Foo
Foo

>> patt=re.compile (' foo ') # #把foo编译成二进制, passed to Patt
>> m=patt.match (' food ') # #在food内容中匹配到foo, passed to M
>> Print M.group () # #显示m的内容
Foo

>> mylist=re.split ('. | -', ' Hello-world.data ') # #使用. Or-as a delimiter, divide the string into a list and give the result to MyList
>> Print MyList
[' Hello ', ' world ', ' data ']

>> m=re.sub (' X ', ' mr.smith ', ' Attn:x\ndearx ') # #把X替换成Mr. Smith
>> Print M
Attn:Mr.smith
Dearmr.smith

###################################################
Use awk to count the number of IPs in the log content
awk ' {ip[$1]++} end{for (i in IP) {print i,ip[i]}} ' per IP access count

###################################################
Count the number of browsers accessed with Firefox and Curl
#!/usr/bin/python
#coding: Utf-8
Import re
Z=0
File1=open ('/var/log/httpd/access_log ')
For I in File1:
X=re.search (' Firefox ', i)
If x:
Z+=1
File1.close ()
print ' Number of Firefox is%d '%z
G=0
File2=open ('/var/log/httpd/access_log ')
For I in File2:
X=re.search (' curl ', i)
If x:
G+=1
File2.close ()
print ' number of curl is%d '%g
#################################
Relative to the previous script simply some dictionary {' subscript ': value, ' subscript ': Value,.....} dic.get (key,0) subscript key to take key (subscript) value, no take 0
#!/usr/bin/python
#coding: Utf-8
Import re
dic={} # # #为字典
Data=open ('/var/log/httpd/access_log ')
For I in data:
m = Re.search (' (firefox|curl) ', i) # #把匹配的内容给m
If M: # #如果m存在, go on down here.
Key=m.group () # # #取出m的内容, become key
Dic[key]=dic.get (key,0) +1 # # #累加dic字典下标firefox的值
Print dic
###########################################
Python Auto Ping Master and
#!/usr/bin/python
#coding: Utf-8
Import subprocess
def myping (x):
M=subprocess.call (' ping-c2-i0.5-w2 w%s &>/dev/null '%x,shell=true)
If m==0:
Print '%s is up '%x
Else
Print '%s is down '%x
ip=[' 176.121.205.%s '%i for I in xrange (1,100)] # #定义列表并赋值
For j in IP: # # #循环列表
Myping (j)
#################################################
Multi-process [each process, has its own memory]
Multithreading [Share a piece of memory]

Multi-threaded ping host faster than above
#!/usr/bin/python
#coding: Utf-8
Import threading
Import subprocess
def myping (x):
M=subprocess.call (' ping-c2%s &>/dev/null '%x,shell=true)
If m==0:
Print '%s is up '%x
Else
Print '%s is down '%x
ip=[' 176.121.205.%s '%i for I in Xrange (1,254)]
For-J in IP:
A=threading. Thread (Target=myping,args=[j])
A.start ()
#################################################
Execute commands with multi-threaded remote hosts
#!/usr/bin/python
#coding: Utf-8
Import Paramiko
Import threading
def myssh (x): # #定义函数
host = x # #远程的主机ip
SSH = Paramiko. Sshclient () # #开启客户端 assigning variables to SSH
Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) # #自动创建远程密钥
Ssh.connect (host,username= ' root ', password= ' Taren1 ') # #连接输入用户名密码
Ssh.exec_command (' mkdir/root/desktop/Go to this Tour ') # #远程执行命令
b=[' 176.121.205.%d '%i for I in Xrange (23,60)] # #利用for循环创建列表
For j in B: # #利用for循环取出列表, take one loop at a time
A=threading. Thread (Target=myssh,args=[j])
A.start ()

Regular expressions

Python errors and exceptions, re-modules, multi-threading, Paramiko modules

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.