Jupyter/IPython SList ::从外壳执行操作符“!"获取未标记的输出 [英] Jupyter / IPython SList :: Obtaining non-tokenized output from the shell execute operator "!"
问题描述
在Jupyter Notebook Python Cell
中运行shell命令时,如下所示:
When shell commands are run within a Jupyter Notebook Python Cell
, like this:
output = ! some-shell-command
每一行都在称为SList
的list
IPython
数据结构中捕获.例如:
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:
print(output)
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 ::从外壳执行操作符“!"获取未标记的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!