Python±Ê¼Ç£¨10£©
PythonÖеÄÒì³£
µ±ÄãµÄ³ÌÐòÖгöÏÖijЩÒì³£µÄ×´¿öµÄʱºò£¬Òì³£¾Í·¢ÉúÁË¡£
Ò».´¦ÀíÒì³£
ÎÒÃÇ¿ÉÒÔʹÓÃtry..exceptÓï¾äÀ´´¦ÀíÒì³£¡£ÎÒÃǰÑͨ³£µÄÓï¾ä·ÅÔÚtry-¿éÖУ¬¶ø°ÑÎÒÃǵĴíÎó´¦ÀíÓï¾ä·ÅÔÚexcept-¿éÖС£
ÀýÈç:
#!/usr/bin/python
# Filename: try_except.py
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?'
sys.exit() # exit the program
except:
print '\nSome error/exception occurred.'
# here, we are not exiting the program
print 'Done'
Êä³öΪ:
$ python try_except.py
Enter something -->
Why did you do an EOF on me?
$ python try_except.py
Enter something --> Python is exceptional!
Done
¶þ.Òý·¢Òì³£
Äã¿ÉÒÔʹÓÃraiseÓï¾äÒý·¢Òì³£¡£Ä㻹µÃÖ¸Ã÷´íÎó/Òì³£µÄÃû³ÆºÍ°éËæÒì³£´¥·¢µÄÒì³£¶ÔÏó¡£Äã¿ÉÒÔÒý·¢µÄ´íÎó»òÒì³£Ó¦¸Ã·Ö±ðÊÇÒ»¸öError»òExceptionÀàµÄÖ±½Ó»ò¼ä½Óµ¼³öÀà¡£
ÀýÈç:
#!/usr/bin/python
# Filename: raising.py
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
# Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
print 'ShortInputException: The input was of length %d, \
was expecting at least %d' % (x.length, x.atleast)
else:
print 'No exception was raised.'
Êä³öΪ:
$ python raising.py
Enter something -->
Why did you do an EOF on me?
$ python raising.py
Enter something --> ab
ShortInputException: The input was of length 2, was expecting at least 3
$ python raising.py
Enter something --> abc
No exception was raised.
Èý.try..finally
¼ÙÈçÄãÔÚ¶ÁÒ»¸öÎļþµÄʱºò£¬Ï£ÍûÔÚÎÞÂÛÒì³£·¢ÉúÓë·ñµÄÇé¿ö϶¼¹Ø±ÕÎļþ£¬¸ÃÔõô×öÄØ£¿Õâ¿ÉÒÔʹÓÃfinally¿éÀ´Íê³É¡£×¢Ò⣬ÔÚÒ»¸
Ïà¹ØÎĵµ£º
¸Õ¸ÕдÍêPythonǶÈ벿·ÖµÄ¼òµ¥Àý×Ó£¨²î²»¶à¹»ÏÖÔÚÓõÄÀ²~£©£¬½Ó×Å¿´µãʵ¼ÊµÄ¶«Î÷£¬Èç¹ûûÓÐÕâЩӦÓõϰ£¬Ç°ÃæµÄǶÈëҲûÓÐʲôÒâÒ塣ǶÈëµÄÆäËû²¿·ÖÒÔºóÓöµ½ÔÙд£¬²»±ØÒ»ÏÂ×Ó°ÑÄÇЩº¯Êý¶¼Åª¶®£¬ÊǰÉ~
OK£¬À´¿´Python¿âÖÐÎÒÈÏΪ×îºÃÍæµÄÒ»²¿·Ö£¬Ò²¾ÍÊÇPython¶ÔÍøÒ³µÄ²Ù×÷¡£
ÕâÆª¼òµ¥ËµÏÂÈçºÎͨ¹ýÍøÖ·ÏÂÔØÍøÒ³£¬Ç°ÌᵱȻÊÇ ......
1. ´òÓ¡±äÁ¿ºÍ±äÁ¿×ÔÏÔ
>>> myString = 'Hello World!'
>>> print myString
Hello World!
>>> myString
'Hello World!'
ÒòΪ£º print Óï¾äµ÷ÓÃstr()º¯ÊýÏÔʾ¶ÔÏ󣬶ø½»»¥Ê½½âÊÍÆ÷Ôòµ÷ÓÃrepr()º¯ÊýÀ´ÏÔʾ¶ÔÏó
sys.stdout.write('hello')²»»áÔÚĩβ¼ÓÉÏ'\n'£¬¶øprint»á
2. ´òÓ¡Îļþ
hand ......
¿Í»§¸øÒ»¶ÑͼƬҪ´«µ½ºǫ́£¬Í¼Æ¬Ì«´óÁË£¬ÉϰÙÕÅͼÓÃphotoshop¸ÄÌ«Âý£¬¾ÍÏëµ½ÓÃpythonд¸ö¼òµ¥µÄÅú´¦Àí¡£¹¦Äܼòµ¥¾ÍÊǰÑÔͼ°´±ÈÀýËõС£¬´úÂë¸ü¼òµ¥ 20¶àÐС£
# -*- coding: cp936 -*-
import Image
import glob, os
#ͼƬÅú´¦Àí
def timage():
for files in glob.glob('D:\\1\\*.JPG'):
filepath,filena ......
import sys
import os
import datetime
import time
class ArgsDealwith:
def arg_environment(self, args):
filepath = ('PYTHON_PATH', 'path')
for i in filepath:
&nbs ......