Python3.2官方文档翻译--标准库概览(一)


7.1 操作系统接口

Os模块提供主要许多与操作系统交互的函数。

>>> import os

>>> os.getcwd() # Return the current working directory

’C:\\Python31’

>>> os.chdir(’/server/accesslogs’) # Change current working directory

>>> os.system(’mkdir today’) # Run the command mkdir in the system shell

0

一定要用import os 方式代替 from os import *. 这会使os.open()方法覆盖内置的open()函数。因为它们操作有很大的不同。

内置方法dir()和help()方法对交互的使用像os这种大模块非常有用。

>>> import os

>>> dir(os)

>>> help(os)

对于日用文件和目录管理任务,shutill模块提供一个更高级别的并方便使用的接口。

>>> import shutil

>>> shutil.copyfile(’data.db’, ’archive.db’)

>>> shutil.move(’/build/executables’, ’installdir’)

7.2 文件通配符

Glob模块提供一个函数用来从目录通配符搜索中生产文件列表。

>>> import glob

>>> glob.glob(’*.py’)

[’primes.py’, ’random.py’, ’quote.py’]

7.3 命令行参数

共同的工具脚本常常需要提供命令行参数。这些参数作为列表保存在sys模块中argv属性中。例如,接下来输出通过在命令行运行python demo.py one two three 得到的结果。

>>> import sys

>>> print(sys.argv)

[’demo.py’, ’one’, ’two’, ’three’]

Getopt模块用Unix的习惯getopt()函数来运行sys.argv. 在argparse模块提供了许多更加作用强大和灵活的命令行操作。

7.4 错误输出重定向和程序终止

Sys模块还包括许多属性如 stdin,stdout和stderr。后面的属性通常用来抛出警告或者错误信息,当stdout重定向时候也可以看到错误信息。

终止脚本的最直接方法就是用sys.exit()方法。

>>> sys.stderr.write(’Warning, log file not found starting a new one\n’)

Warning, log file not found starting a new one

评论关闭