回目录
相当于C++中的类库, 例如你自己写的lib, STL等.
#!/usr/bin/python # Filename: using_sys.py import sys # 导入库 print('The command line arguments are:') for i in sys.argv: print(i) print('\nThe PYTHONPATH is', sys.path)
这里,当我们执行python using_sys.py we are arguments的时候,我们使用python命令运行using_sys.py模块,后面跟着的内容被作为参数传递给程序。Python为我们把它存储在sys.argv变量中。
记住,脚本的名称总是sys.argv列表的第一个参数。所以,在这里,'using_sys.py'是sys.argv[0]、'we'是sys.argv[1]、'are'是sys.argv[2]以及'arguments'是sys.argv[3]。注意,Python从0开始计数,而非从1开始。
sys.path包含输入模块的目录名列表。我们可以观察到sys.path的第一个字符串是空的——这个空的字符串表示当前目录也是sys.path的一部分,这与PYTHONPATH环境变量是相同的。这意味着你可以直接输入位于当前目录的模块。否则,你得把你的模块放在sys.path所列的目录之一。
模块的__name__
每个模块都有一个名称,在模块中可以通过语句来找出模块的名称。这在一个场合特别有用——就如前面所提到的,当一个模块被第一次输入的时候,这个模块的主块将被运行。假如我们只想在程序本身被使用的时候运行主块,而在它被别的模块输入的时候不运行主块,我们该怎么做呢?这可以通过模块的__name__属性完成。
#!/usr/bin/python # Filename: using_name.py if __name__ == '__main__': print('This program is being run by itself') else: print('I am being imported from another module') 看如下输入命令: $ python using_name.py This program is being run by itself $ python >>> import using_name I am being imported from another module >>>
创建你自己的模块是十分简单的,你一直在这样做!每个Python程序也是一个模块。你已经确保它具有.py扩展名了
#!/usr/bin/python # Filename: using_name.py if __name__ == '__main__': print('This program is being run by itself') else: print('I am being imported from another module') 看如下输入命令: $ python using_name.py This program is being run by itself $ python >>> import using_name I am being imported from another module >>>
它与我们普通的Python程序相比并没有什么特别之处
看怎么使用上面的模块
#!/usr/bin/python # Filename: mymodule_demo.py import mymodule # 导入自己的模块 mymodule.sayhi() # 调用模块中的函数 print('Version', mymodule.version) # 调用模块中的变量
你可以使用内建的dir函数来列出模块定义的标识符。标识符有函数、类和变量。
当你为dir()提供一个模块名的时候,它返回模块定义的名称列表。如果不提供参数,它返回当前模块中定义的名称列表。
使用dir函数
例8.4 使用dir函数
$ python >>> import sys >>> dir(sys) # get list of attributes for sys module ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'meta_path','modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions'] >>> dir() # get list of attributes for current module ['__builtins__', '__doc__', '__name__', 'sys'] >>> >>> a = 5 # create a new variable 'a' >>> dir() ['__builtins__', '__doc__', '__name__', 'a', 'sys'] >>> >>> del a # delete/remove a name >>> >>> dir() ['__builtins__', '__doc__', '__name__', 'sys'] >>>
#!/usr/bin/python # Filename: using_list.py # This is my shopping list shoplist = ['apple', 'mango', 'carrot', 'banana'] # 定义一个列表 print('I have', len(shoplist), 'items to purchase.') # 列表长度 print('These items are:') for item in shoplist: # 循环打印列表项 print(item) print('\nI also have to buy rice.') shoplist.append('rice') # 在列表后面追加一项 print('My shopping list is now', shoplist) # 显示列表 print('I will sort my list now') shoplist.sort() # 排序 print('Sorted shopping list is', shoplist) print('The first item I will buy is', shoplist[0]) # 可以使用索引, 像C++的数组 olditem = shoplist[0] del shoplist[0] # 删除列表的一项 print('I bought the', olditem) print('My shopping list is now', shoplist)
元组和列表十分类似,只不过元组和字符串一样是 不可变的 即你不能修改元组。元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。
#!/usr/bin/python # Filename: using_tuple.py zoo = ('wolf', 'elephant', 'penguin') # 定义一个元组 print('Number of animals in the zoo is', len(zoo)) new_zoo = ('monkey', 'dolphin', zoo) # 定义一个元组, 其中一个项本身就是一个元组 print('Number of animals in the new zoo is', len(new_zoo)) print('All animals in new zoo are', new_zoo) print('Animals brought from old zoo are', new_zoo[2]) # 可以使用索引 print('Last animal brought from old zoo is', new_zoo[2][2]) # 有点像二维数组啊.
另一个文件
#!/usr/bin/python # Filename: print_tuple.py age = 22 name = 'Swaroop' print('Why is %s playing with that python?' % name) # 像不像C++ 的printf啊 print('%s is %d years old' % (name, age)) # 元组的显示
就是STL的 map了, key : vlue对应关系, key是唯一的.
键值对在字典中以这样的方式标记:d = {key1 : value1, key2 : value2 }。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。
记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。
字典是dict类的实例/对象。
#!/usr/bin/python # Filename: using_dict.py # 'ab' is short for 'a'ddress'b'ook ab = {'Swaroop' : '[email protected]', 'Larry' : '[email protected]', 'Matsumoto' : '[email protected]', 'Spammer' : '[email protected]'} # 字典的定义 print("Swaroop's address is %s" % ab['Swaroop']) # 可以像数组一样使用, 索引是key # Adding a key/value pair ab['Guido'] = '[email protected]' # 赋值 # Deleting a key/value pair del ab['Spammer'] # 删除 print('\nThere are %d contacts in the address-book\n' % len(ab)) for name, address in ab.items(): # 注意这个是怎么循环的 print('Contact %s at %s' % (name, address)) if 'Guido' in ab: # OR ab.has_key('Guido') # 看 print("\nGuido's address is %s" % ab['Guido']) 输出 $ python using_dict.py Swaroop's address is [email protected] There are 4 contacts in the address-book Contact Swaroop at [email protected] Contact Matsumoto at [email protected] Contact Larry at [email protected] Contact Guido at [email protected] Guido's address is [email protected]
列表、元组和字符串都是序列,但是序列是什么,它们为什么如此特别呢?序列的两个主要特点是索引操作符和切片操作符。
索引操作符让我们可以从序列中抓取一个特定项目。切片操作符让我们能够获取序列的一个切片,即一部分序列。
使用序列
例9.5 使用序列
#!/usr/bin/python # Filename: seq.py shoplist = ['apple', 'mango', 'carrot', 'banana'] # Indexing or 'Subscription' operation print('Item 0 is', shoplist[0]) print('Item 1 is', shoplist[1]) print('Item 2 is', shoplist[2]) print('Item 3 is', shoplist[3]) print('Item -1 is', shoplist[-1]) print('Item -2 is', shoplist[-2]) # Slicing on a list print('Item 1 to 3 is', shoplist[1:3]) print('Item 2 to end is', shoplist[2:]) print('Item 1 to -1 is', shoplist[1:-1]) print('Item start to end is', shoplist[:]) # Slicing on a string name = 'swaroop' print('characters 1 to 3 is', name[1:3]) print('characters 2 to end is', name[2:]) print('characters 1 to -1 is', name[1:-1]) print('characters start to end is', name[:]) 输出 $ python seq.py Item 0 is apple Item 1 is mango Item 2 is carrot Item 3 is banana Item -1 is banana Item -2 is carrot Item 1 to 3 is ['mango', 'carrot'] Item 2 to end is ['carrot', 'banana'] Item 1 to -1 is ['mango', 'carrot'] Item start to end is ['apple', 'mango', 'carrot', 'banana'] characters 1 to 3 is wa characters 2 to end is aroop characters 1 to -1 is waroo characters start to end is swaroop
例9.6 对象与参考
#!/usr/bin/python # Filename: reference.py print('Simple Assignment') shoplist = ['apple', 'mango', 'carrot', 'banana'] mylist = shoplist # mylist is just another name pointing to the same object! # 等于是指针赋值. del shoplist[0] print('shoplist is', shoplist) print('mylist is', mylist) # notice that both shoplist and mylist both print the same list without # the 'apple' confirming that they point to the same object print('Copy by making a full slice') mylist = shoplist[:] # make a copy by doing a full slice 这里是深层赋值 del mylist[0] # remove first item print('shoplist is', shoplist) print('mylist is', mylist) # notice that now the two lists are different 输出 $ python reference.py Simple Assignment shoplist is ['mango', 'carrot', 'banana'] mylist is ['mango', 'carrot', 'banana'] Copy by making a full slice shoplist is ['mango', 'carrot', 'banana'] mylist is ['carrot', 'banana']
记住列表的赋值语句不创建拷贝。你得使用切片操作符来建立序列的拷贝。
字符串也是对象,同样具有方法。这些方法可以完成包括检验一部分字符串和去除空格在内的各种工作。你在程序中使用的字符串都是str类的对象。这个类的一些有用的方法会在下面这个例子中说明。如果要了解这些方法的完整列表,请参见help(str)。
例9.7 字符串的方法
#!/usr/bin/python # Filename: str_methods.py name = 'Swaroop' # This is a string object if name.startswith('Swa'): print('Yes, the string starts with "Swa"') if 'a' in name: print('Yes, it contains the string "a"') if name.find('war') != -1: print('Yes, it contains the string "war"') delimiter = '_*_' mylist = ['Brazil', 'Russia', 'India', 'China'] print(delimiter.join(mylist)) 输出 $ python str_methods.py Yes, the string starts with "Swa" Yes, it contains the string "a" Yes, it contains the string "war" Brazil_*_Russia_*_India_*_China
这里,我们看到使用了许多字符串方法。startwith方法是用来测试字符串是否以给定字符串开始。in操作符用来检验一个给定字符串是否为另一个字符串的一部分。find方法用来找出给定字符串在另一个字符串中的位置,或者返回-1以表示找不到子字符串。str类也有以一个作为分隔符的字符串join序列的项目的整洁的方法,它返回一个生成的大字符串。
#!/usr/bin/python # Filename: backup_ver1.py #导入模块 import os import time # 1. The files and directories to be backed up are specified in a list. # Unix/Linux , use source = ['/home/swaroop/byte', '/home/swaroop/bin'] # Windows, use source = ['C:\\Documents\\', 'D:\\Work\\'] source = ['C:\TestD\\', 'C:\TestW\\'] sourceFile = 'C:\\TestD\TT.txt' # 2. The backup must be stored in a main backup directory target_dir = 'C:\\TestW\\' # Remember to change this to what you will be using # 3. The files are backed up into a zip file. # 4. The name of the zip archive is the current date and time target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.rar' # 字符串的处理 # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command = 'rar a "%s" "%s"' % (target, sourceFile) # 字符串才处理 print(zip_command) # Run the backup if os.system(zip_command) == 0: # 调用命令行 print('Successful backup to', target) else: print('Backup FAILED')
#!/usr/bin/python # Filename: backup_ver1.py import os import time # 1. The files and directories to be backed up are specified in a list. # Unix/Linux , use source = ['/home/swaroop/byte', '/home/swaroop/bin'] # Windows, use source = [r'C:\\Documents\\', r'D:\\Work\\'] source = [r'C:\TestD\\', r'C:\TestW\\'] sourceFile = 'C:\\TestD\TT.txt' # 2. The backup must be stored in a main backup directory target_dir = 'C:\\TestW\\' # Remember to change this to what you will be using # 3. The files are backed up into a zip file. # 4. The current day is the name of the subdirectory in the main directory today = target_dir + time.strftime('%Y%m%d') # 日期 # The current time is the name of the zip archive now = time.strftime('%H%M%S') # 时间 # Create the subdirectory if it isn't already there if not os.path.exists(today): os.mkdir(today) # make directory # 创建目录 print('Successfully created directory', today) # 3. The files are backed up into a zip file. # 4. The name of the zip archive is the current date and time target = today + os.sep + now + '.rar' # os.sep是一个斜干吧 # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command = 'rar a "%s" "%s"' % (target, sourceFile) print(zip_command) # Run the backup if os.system(zip_command) == 0: print('Successful backup to', target) else: print('Backup FAILED')
(不要加入中文注释, 否则会错误, 如果文件保存为Unicode格式就可以输入中文, 在使用了Utf8格式保存后, 代码的变量也可以使用中文来命名, 强啊)
#!/usr/bin/python # Filename: backup_ver3.py import os import time # 1. The files and directories to be backed up are specified in a list. # Unix/Linux , use source = ['/home/swaroop/byte', '/home/swaroop/bin'] # Windows, use source = [r'C:\\Documents\\', r'D:\\Work\\'] source = [r'C:\TestD\\', r'C:\TestW\\'] sourceFile = 'C:\\TestD\TT.txt' # 2. The backup must be stored in a main backup directory target_dir = 'C:\\TestW\\' # Remember to change this to what you will be using # 3. The files are backed up into a zip file. # 4. The current day is the name of the subdirectory in the main directory today = target_dir + time.strftime('%Y%m%d') # The current time is the name of the zip archive now = time.strftime('%H%M%S') comment = input('Enter a comment --> ') 内容 = 'abcde' print(内容) # Create the subdirectory if it isn't already there if not os.path.exists(today): os.mkdir(today) # make directory print('Successfully created directory', today) if len(comment) == 0: # check if a comment was entered target = today + os.sep + now + '.rar' else: target = today + os.sep + now + '_' + \ comment.replace(' ', '_') + '.rar' # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command = 'rar a "%s" "%s"' % (target, sourceFile) print(zip_command) # Run the backup if os.system(zip_command) == 0: print('Successful backup to', target) else: print('Backup FAILED')