Python pipes模块如何实现'cat'命令

1 投票
1 回答
538 浏览
提问于 2025-04-16 23:54

我正在尝试在Python中做这个:

cat foo | ssh me@xxxx hadoop fs -put - bar/foo

我最开始试过用check_call:

foo = 'foo'
subprocess.check_call(['cat', foo, '|','ssh',os.environ['USER']+'@'+hadoopGateway,'hadoop','fs','-put', '-', inputArgs.targetDir+'/'+foo])

但是出现了这个错误:

cat: invalid option -- 'p'

我查看了Python的pipes模块文档,并在命令行中试了一下,但我不明白如何在没有输出文件的情况下启动它,就像例子中那样。

>>> t = pipes.Template()
>>> t.prepend('cat foo', '.-')
>>> t.append('hadoop fs -put - bar/foo', '-.') # what next

显然我漏掉了什么。

1 个回答

4

你不需要用到 cat 或者管道;你只需要把文件作为标准输入提供给 ssh 命令就可以了。在命令行中,你可以这样做:

ssh ${USER}@${hadoopGateway} hadoop fs -put - ${targetDir}/foo < foo

如果你用 Python 的 subprocess 模块,稍微复杂一点,但也不难:

foo='foo'
subprocess.check_call(['ssh',
                       os.environ['USER']+'@'+hadoopGateway,
                       'hadoop', 'fs', '-put', '-', inputArgs.targetDir+'/'+foo],
                      stdin=open(foo, 'r'))

撰写回答