Jupyter/IPython SList ::从shell执行操作符& quot !!& quot;中获取未标记的输出 [英] Jupyter / IPython SList :: Obtaining non-tokenized output from the shell execute operator "!"
问题描述
在 Jupyter Notebook Python单元格
中运行shell命令时,如下所示:
When shell commands are run within a Jupyter Notebook Python Cell
, like this:
output =!some-shell-command
发射到标准输出( stdout
)的每一行都被捕获在 list
like IPython
data-称为 SList
的结构.例如:
each line emitted to the standard output (stdout
) is captured in a list
like IPython
data-structure called a SList
. For instance:
output = !echo -e 'line1\nline2\nline3'
print(output) # A IPython SList data-structure.
['line1','line2','line3']
但是,有时您希望保留原始的字符串输出格式,而无需将其标记化为列表,如下所示:
Sometimes, however, you want to preserve the original string output format, without tokenization into a list, like this:
打印(输出)
line1
line2
line3
示例:对于结构化JSON输出(它是包含许多换行符的字符串),您不希望发生这种标记化.
然后,如何使用!
运算符在 Jupyter Notebooks
中执行shell命令,并检索未标记的输出(如上)?
How, then, can I execute shell commands in Jupyter Notebooks
using the !
operator, and retrieve un-tokenized output (like above)?
理想情况下,解决方案应该是 Jupyter Notebooks
中的本地解决方案.
Ideally, the solution would be something native in Jupyter Notebooks
.
谢谢!
推荐答案
SList
具有许多属性,这些属性以各种形式返回:
The SList
has a number of properties, that return it in various forms:
https://gist.github.com/parente/b6ee0efe141822dfa18b6feeda0a45e5
In [151]: ret = !ls *.json
In [152]: ret
Out[152]: ['foo1.json', 'foo.json', 'logins.json', 'stack56532806.json']
作为列表
In [153]: ret.l
Out[153]: ['foo1.json', 'foo.json', 'logins.json', 'stack56532806.json']
以换行符分隔的字符串:
as newline separated string:
In [154]: ret.n
Out[154]: 'foo1.json\nfoo.json\nlogins.json\nstack56532806.json'
以空格分隔:
In [155]: ret.s
Out[155]: 'foo1.json foo.json logins.json stack56532806.json'
In [156]: type(ret)
其文档
In [158]: ret?
Type: SList
String form: ['foo1.json', 'foo.json', 'logins.json', 'stack56532806.json']
Length: 4
File: /usr/local/lib/python3.6/dist-packages/IPython/utils/text.py
Docstring:
List derivative with a special access attributes.
These are normal lists, but with the special attributes:
* .l (or .list) : value as list (the list itself).
* .n (or .nlstr): value as a string, joined on newlines.
* .s (or .spstr): value as a string, joined on spaces.
* .p (or .paths): list of path objects (requires path.py package)
Any values which require transformations are computed only once and
cached.
这篇关于Jupyter/IPython SList ::从shell执行操作符& quot !!& quot;中获取未标记的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!