36.11. 管道-Shell 管道的接口

源代码: Lib/pipes.py


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

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

  • 类别 pipes. Template
    • 管道的抽象。

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'
  • pipes. quote(* s *)
    • 从 2.7 版开始不推荐使用:在 Python 2.7 之前,此Function尚未公开记录。最后,它在 python_ 3.3 中公开公开为shlex模块中的quote函数。

返回字符串* 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. 模板对象

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

  • Template. reset ( )

    • 将管道模板还原到其初始状态。
  • Template. clone ( )

    • 返回一个等效的新管道模板。
  • Template. debug(* flag *)

    • 如果* flag *为 true,请打开调试。否则,请关闭调试。调试打开时,将打印要执行的命令,并为 Shell 提供set -x命令,以使其更详细。
  • Template. append(* cmd kind *)

    • 最后追加一个新动作。 * cmd *变量必须是有效的 bourne shell 命令。 * kind *变量由两个字母组成。

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

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

  • Template. prepend(* cmd kind *)

    • 在开始处添加一个新动作。有关参数的说明,请参见append()
  • Template. open(* file mode *)

    • 返回一个类似文件的对象,打开到* file *,但可以从管道中读取或写入。请注意,只能提供'r''w'中的一个。
  • Template. copy(* infile outfile *)

    • pass管道将* infile 复制到 outfile *。