如何在python中获得当前的jupyter笔记本服务器?

2024-04-23 23:09:55 发布

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

如何获取python中当前运行的Jupyter笔记本服务器的列表?

有一个jupyter-notebook命令列出当前笔记本服务器

machinename:~ username$ jupyter-notebook list
 http://localhost:8888 :: /Users/username/your/notebook/path
 http://localhost:8889 :: /Users/username/your/other/notebook/path
 ...

在python中,如果不进入命令行并解析输出,怎么能做到这一点呢?


Tags: path命令服务器localhosthttp列表yourusername
3条回答

从python访问正在运行的笔记本服务器列表

可以通过实际的python notebookapp程序从python内部通过调用list_running_servers()来访问正在运行的笔记本服务器列表。

from notebook import notebookapp
servers = list(notebookapp.list_running_servers())
print servers

[{u'base_url': u'/',
  u'hostname': u'localhost',
  u'notebook_dir': u'/Users/username/your/notebook/path',
  u'pid':123,
  u'port': 8888,
  u'secure': False,
  u'url': u'http://localhost:8888/'},
 ...
 {u'base_url': u'/',
  u'hostname': u'localhost',
  u'notebook_dir': u'/Users/username/your/other/notebook/path',
  u'pid': 1234,
  u'port': 8889,
  u'secure': True,
  u'url': u'http://localhost:8889/'}]

这也提供了比命令行界面更多的信息。\o/-很好!

可以使用以下命令从命令行执行此操作:

find `jupyter --runtime-dir` -mtime -5 | grep nbserver | xargs cat

jupyter --runtime-dir返回Jupyter存储大量关于内核和Jupyter服务器的JSON元数据文件的目录。 find-mtime参数使其仅显示最近5天内修改的文件。

在我的MacBook上,我得到了以下结果:

{
  "base_url": "/",
  "url": "http://localhost:8888/",
  "port": 8888,
  "pid": 50017,
  "secure": false,
  "hostname": "localhost",
  "notebook_dir": "/Users/myusername"
}{
  "base_url": "/",
  "hostname": "localhost",
  "notebook_dir": "/Users/myusername",
  "password": false,
  "pid": 63644,
  "port": 8889,
  "secure": false,
  "token": "058fc6cbd6d793c6ddda420ff6d5d3c42819be526b68602d",
  "url": "http://localhost:8889/"
}

(我有两个不同版本的Jupyter环境)

只需使用jupyter notebook list就可以了。它列出了所有正在运行的服务器:

<frankliuao/Volumes/Ao_HardDisk/$> jupyter notebook list
Currently running servers:
http://localhost:8889/? 
token=476f392542ef41bc020cf26c2ddac0128ee42c0d3c542ac7 :: 
/Users/frankliuao/Downloads/
http://localhost:8888/? 
token=b1a33f34b80ddfa2476550671599b566131e3d875d9d4250 :: 
/Users/frankliuao/Desktop

如果您想用Python获得这些信息,可以使用popen来执行Shell命令。

相关问题 更多 >