元组拆包结合ipython shell转义

时间:2014-02-04 11:23:12

标签: python bash ipython iterable-unpacking

如何在ipython中解压缩shell转义的输出?

示例(工作):

In [1]: !locate .hgrc
/home/wim/.hgrc
/usr/share/doc/mercurial-common/examples/sample.hgrc

In [2]: hgrcs = !locate .hgrc

In [3]: hgrcs[0]
Out[3]: '/home/wim/.hgrc'

但这不起作用:

In [4]: hgrc0, *rest = !locate .hgrc
  File "<ipython-input-4-e8900264b4a8>", line 1
    hgrc0, *rest = !locate .hgrc
                   ^
SyntaxError: invalid syntax

也不行:

In [13]: x = !locate .hgrc | head -1

In [14]: x
Out[14]: ['/home/wim/.hgrc']

In [15]: x, = !locate .hgrc | head -1
  File "<ipython-input-15-524d2c9ab16f>", line 1
    x, = !locate .hgrc | head -1
         ^
SyntaxError: invalid syntax

Python 3.3.2+上的IPython 0.13.2。

2 个答案:

答案 0 :(得分:5)

Icky,但对于这个特殊情况:

hgrc0, _ = !locate .hgrc | head -1 | printf '%s\n_' $(cat)

答案 1 :(得分:2)

我在提交issue之后不久就解决了这个问题。

https://github.com/ipython/ipython/pull/5321