36.11. 管道-Shell 管道的接口

源代码: Lib/pipes.py


pipes模块定义了一个类,用于抽象* pipeline *的概念—管道从一个文件到另一个文件的一系列转换。

由于该模块使用 /bin/sh 命令行,因此需要用于os.system()os.popen()的 POSIX 或兼容 Shell。

Example:

>>> import pipes
>>> t = pipes.Template()
>>> t.append('tr a-z A-Z', '--')
>>> f = t.open('pipefile', 'w')
>>> f.write('hello world')
>>> f.close()
>>> open('pipefile').read()
'HELLO WORLD'

返回字符串* s *的脱壳版本。返回的值是一个字符串,在不能使用列表的情况下,可以安全地用作 shell 命令行中的一个标记。

这个习惯用法是不安全的:

>>> filename = 'somefile; rm -rf ~'
>>> command = 'ls -l {}'.format(filename)
>>> print command  # executed by a shell: boom!
ls -l somefile; rm -rf ~

quote()可让您堵塞安全漏洞:

>>> command = 'ls -l {}'.format(quote(filename))
>>> print command
ls -l 'somefile; rm -rf ~'
>>> remote_command = 'ssh home {}'.format(quote(command))
>>> print remote_command
ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''

引用与 UNIX shell 和shlex.split()兼容:

>>> remote_command = shlex.split(remote_command)
>>> remote_command
['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
>>> command = shlex.split(remote_command[-1])
>>> command
['ls', '-l', 'somefile; rm -rf ~']

36.11.1. 模板对象

模板对象有以下几种方法:

第一个字母可以是'-'(表示命令读取标准 Importing),'f'(表示命令读取命令行上的给定文件)或'.'(表示命令不读取 Importing,因此必须是第一个字母) )

同样,第二个字母可以是'-'(表示命令将命令写入标准输出),'f'(表示命令在命令行中写入文件)或'.'(表示命令不写入任何内容,因此必须)最后。)

首页