【问题标题】:Pass output of 'find' command to Python with docopt (issue with spaces)使用 docopt 将“find”命令的输出传递给 Python(空格问题)
【发布时间】:2020-01-17 09:33:47
【问题描述】:

考虑一下这个简单的 Python 命令行脚本:

"""foobar
  Description

Usage:
  foobar [options] <files>...

Arguments:
  <files>         List of files.

Options:
  -h, --help      Show help.
      --version   Show version.
"""

import docopt

args = docopt.docopt(__doc__)
print(args['<files>'])

并考虑到我在一个文件夹中有以下文件:

  • file1.pdf
  • file 2.pdf

现在我想将find 命令的输出传递给我的简单命令行脚本。但是当我尝试

foobar `find . -iname '*.pdf'`

我没有得到我想要的文件列表,因为输入是按空格分割的。 IE。我明白了:

['./file', '2.pdf', './file1.pdf']

我怎样才能正确地做到这一点?

【问题讨论】:

    标签: python linux command-line docopt


    【解决方案1】:

    这不是 Python 问题。这就是关于 shell 如何标记命令行的全部内容。空格用于分隔命令参数,这就是为什么 file 2.pdf 显示为两个单独的参数。

    你可以结合findxargs来做你想做的事情:

    find . -iname '*.pdf' -print0 | xargs -0 foobar
    

    find 的 -print0 参数告诉它输出由 ASCII NUL 字符而不是空格分隔的文件名,xargs-0 参数告诉它期待这种形式的输入。 xargs 然后使用正确的参数调用您的 foobar 脚本。

    比较:

    $ ./foobar $(find . -iname '*.pdf' )
    ['./file', '2.pdf', './file1.pdf']
    

    收件人:

    $ find .  -iname '*.pdf' -print0 | xargs -0 ./foobar
    ['./file 2.pdf', './file1.pdf']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 1970-01-01
      • 2020-11-19
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      相关资源
      最近更新 更多