[关闭]
@Frankchen 2016-03-28T08:10:29.000000Z 字数 2879 阅读 1423

Python Utilities

python


File System -- os, os.path, shutil

osos.path 模块包括许多与文件系统交互的函数。 shutil 模块能copy文件。

  1. ## Example pulls filenames from a dir, prints their relative and absolute paths
  2. def printdir(dir):
  3. filenames = os.listdir(dir)
  4. for filename in filenames:
  5. print filename ## foo.txt
  6. print os.path.join(dir, filename) ## dir/foo.txt (relative to current dir)
  7. print os.path.abspath(os.path.join(dir, filename)) ## /home/nick/dir/foo.txt

Running External Processes -- commands

commands 模块是一种简单的运行外部命令并且抓取它的输出的方法。

  1. ## Given a dir path, run an external 'ls -l' on it --
  2. ## shows how to call an external program
  3. def listdir(dir):
  4. cmd = 'ls -l ' + dir
  5. print "Command to run:", cmd ## good to debug cmd before actually running it
  6. (status, output) = commands.getstatusoutput(cmd)
  7. if status: ## Error case, print the command's output to stderr and exit
  8. sys.stderr.write(output)
  9. sys.exit(1)
  10. print output ## Otherwise do something with the command's output

Exceptions

一个exception代表一个在某行代码中阻止常规运行的 run-time错误并把控制转向错误码。比如,run-time错误可能是因为程序中用到的某个变量没有值(ValueError),或者文件打开操作错误因为那儿没有这个文件存在(IOError)。
没有error handing 代码,一个 run-time exception只是暂停程序并且返回错误信息,而我们可以添加'try/except'结构来解决exception如:

  1. try:
  2. ## Either of these two lines could throw an IOError, say
  3. ## if the file does not exist or the read() encounters a low level error.
  4. f = open(filename, 'rU')
  5. text = f.read()
  6. f.close()
  7. except IOError:
  8. ## Control jumps directly to here if any of the above lines throws IOError.
  9. sys.stderr.write('problem reading:' + filename)
  10. ## In any case, the code then continues with the line after the try/except

try部分包括了可能跑出exception的代码。而except部分保持代码运行如果那里有exception,若没有exception,except部分被跳过。

HTTP -- urllib and urlparse

urllib模块提供了url取得:让一个url看起来像能读取的文件
urlparse 能切分合并url。

  1. ## Given a url, try to retrieve it. If it's text/html,
  2. ## print its base url and its text.
  3. def wget(url):
  4. ufile = urllib.urlopen(url) ## get file-like object for url
  5. info = ufile.info() ## meta-info about the url content
  6. if info.gettype() == 'text/html':
  7. print 'base url:' + ufile.geturl()
  8. text = ufile.read() ## read all its text
  9. print text

上面的代码不包括错误handling,下面加上try/except:

  1. ## Version that uses try/except to print an error message if the
  2. ## urlopen() fails.
  3. def wget2(url):
  4. try:
  5. ufile = urllib.urlopen(url)
  6. if ufile.info().gettype() == 'text/html':
  7. print ufile.read()
  8. except IOError:
  9. print 'problem reading url:', url
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注