jupyter notebook -- OSError: [Errno 49] Can't assign requested address

前言

這是筆者在命令行裡輸入jupyter notebook試著啟動jupyter notebook時所發生的錯誤。

錯誤訊息

Traceback (most recent call last):
File “/anaconda3/bin/jupyter-notebook”, line 11, in <module>
sys.exit(main())
File “/anaconda3/lib/python3.6/site-packages/jupyter_core/application.py”, line 266, in launch_instance
return super(JupyterApp, cls).launch_instance(argv=argv, **kwargs)
File “/anaconda3/lib/python3.6/site-packages/traitlets/config/application.py”, line 657, in launch_instance
app.initialize(argv)
File “<decorator-gen-7>”, line 2, in initialize
File “/anaconda3/lib/python3.6/site-packages/traitlets/config/application.py”, line 87, in catch_config_error
return method(app, *args, **kwargs)
File “/anaconda3/lib/python3.6/site-packages/notebook/notebookapp.py”, line 1537, in initialize
self.init_webapp()
File “/anaconda3/lib/python3.6/site-packages/notebook/notebookapp.py”, line 1321, in init_webapp
self.http_server.listen(port, self.ip)
File “/anaconda3/lib/python3.6/site-packages/tornado/tcpserver.py”, line 144, in listen
sockets = bind_sockets(port, address=address)
File “/anaconda3/lib/python3.6/site-packages/tornado/netutil.py”, line 163, in bind_sockets
sock.bind(sockaddr)
OSError: [Errno 49] Can’t assign requested address

發生原因

jupyter notebook預設的ip是localhost,但是可能由原某些原因導致localhost無法被正確解析。因此我們可以自行設定jupyter notebook所使用的ip來避開這個問題。

解決辦法

單次的解決辦法(使用以下的其中之一)

jupyter notebook --ip=*
jupyter notebook --ip=0.0.0.0
jupyter notebook --ip=127.0.0.1

一勞永逸的解決辦法

先進到個人的家目錄下

cd ~ 

產生jupyter的config檔,即~/.jupyter/jupyter_notebook_config.py

jupyter notebook --generate-config 

將jupyter config檔中以#c.NotebookApp.ip開頭的那一行替換為c.NotebookApp.ip = ‘0.0.0.0’,可以使用以下兩種方式:
方法一:使用vim編輯器

vim ~/.jupyter/jupyter_notebook_config.py

然後手動找出該行並替換

方法二:使用sed自動替換

sed -i '.backup' 's/^#c.NotebookApp.ip.*/c.NotebookApp.ip = '0.0.0.0'/g' ~/.jupyter/jupyter_notebook_config.py 

我們可以使用以下指令來檢查執行是否成功:

cat ~/.jupyter/jupyter_notebook_config.py | grep "c.NotebookApp.ip" #c.NotebookApp.ip = '0.0.0.0'

sed指令說明

  • sed代表的是stream editor,可以直接在命令行裡編輯文檔
  • sed command [file …]:對file做一些指令(由command指定)
  • sed [-i extension] command [file …]:in-place(原地)地對file做一些指令(由command指定)
    • -i extension:把原來的檔案備份為<filename><extension>
  • command裡的s函數:s代表的是替換函數,把第一筆符合的字串替換掉。(Substitute the replacement string for the first instance of the regular expression in the pattern space.)
    • s/regular expression/replacement/flags:
      • regular expression:這是我們要尋找的目標。
        ^#c.NotebookApp.ip.*:代表以c.NotebookApp.ip開頭的行
      • replacement:要將目標替換成什麼。
        此處將目標替換成c.NotebookApp.ip = ‘0.0.0.0’
      • flags:s函數的flag,代表將所有符合的字串替換掉。

後記

筆者後來試著查看localhost無法被識別的原因,使用ping localhost,發現可以ping得通。
並且在開啟jupyter notebook後,試著將browser的ip改為localhost及127.0.0.1,發現它仍然可以正常運作。
所以問題可能出在jupyter notebook本身而非電腦上localhost設定的問題,這個還需要花時間探討。

猜你喜欢

转载自blog.csdn.net/keineahnung2345/article/details/84333636