Jupyter/IPython SList::从shell执行操作符“”获取未经标记的输出

2024-09-24 10:25:35 发布

您现在位置:Python中文网/ 问答频道 /正文

Jupyter Notebook Python Cell中运行shell命令时,如下所示:

output = ! some-shell-command

发射到标准输出(stdout)的每一行都被捕获到一个类似于IPythonSList数据结构中。例如:

output = !echo -e 'line1\nline2\nline3'
print(output) # A IPython SList data-structure.

['line1', 'line2', 'line3']

但是,有时您希望保留原始字符串输出格式,而不将其标记到列表中,如下所示:

print(output)

line1
line2
line3

示例:对于结构化JSON输出(一个包含许多换行符的字符串),您不希望出现这种标记化

那么,如何使用!操作符在Jupyter Notebooks中执行shell命令,并检索未标记化的输出(如上所述)

理想情况下,解决方案应该是Jupyter Notebooks中的本地解决方案

谢谢大家!


Tags: 字符串标记命令outputipythonjupyter解决方案shell
3条回答

对于这里希望将类型为SList的jupyter标准输出(stdout)转换为JSON的人,我就是这么做的:

import json
output = !command  #output is an SList
j_out = json.dumps(output)  #jout is a str
out_dict = json.loads(j_out) #out_dict is a list 
out_dict[i][j]... #to access list elements

这假设command已将要处理到python字典中的输出适当格式化

SList有许多属性,它们以各种形式返回它:

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']

作为换行符分隔字符串:

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.

使用join()将迭代器组合成字符串

"\n".join(output)

相关问题 更多 >