首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

pipes

源代码: Lib / pipes.py

pipes模块定义了一个类来抽象管道的概念- 从一个文件到另一个文件的一系列转换器。

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

class pipes.Template

管道的抽象。

例:

代码语言:javascript
复制
>>> 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之前,此功能未公开记录。 它最终在Python 3.3中作为shlex模块中的引用函数公开公开。

返回字符串s的shell转义版本。返回的值是一个字符串,可安全地用作shell命令行中的一个标记,用于不能使用列表的情况。

这个习语会是不安全的:

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

quote() 让你接上安全漏洞:

代码语言:javascript
复制
>>> 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()兼容:

代码语言:javascript
复制
>>> 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 ~']

1.模板对象

以下方法的模板对象:

Template.reset()

将管道模板恢复到其初始状态。

Template.clone()

返回一个新的等效管道模板。

Template.debug(flag)

如果标志 为真,则打开调试。否则,关闭调试。打开调试时,将打印要执行的命令,并给shell set -x命令更详细。

Template.append(cmd, kind)

在最后附加一个新动作。在CMD变量必须是一个有效的Bourne shell命令。该变量由两个字母组成。

第一个字母可以是'-'(这意味着命令读取其标准输入)'f'(这意味着命令读取命令行上的给定文件)或'.'(这意味着命令不读取任何输入,因此必须是第一个)。

类似地,第二个字母可以是'-'(这意味着命令写入标准输出)'f'(这意味着命令在命令行上写入文件)或'.'(这意味着该命令不会写入任何内容,因此必须是最后一个)。 )

Template.prepend(cmd, kind)

在开始时添加一个新的动作。请参阅有关append()论据的解释。

Template.open(file, mode)

返回一个类似文件的对象,打开文件,但是读取或写入管道。请注意,只有一个'r''w'可能会被给出。

Template.copy(infile, outfile)

通过管道将infile 复制到outfile

扫码关注腾讯云开发者

领取腾讯云代金券