在jupyter笔记本的单元格内使用sudo

在jupyter笔记本的单元格内使用sudo

问题描述:

我正在尝试为Jupyter笔记本中的平台制作教程

I'm trying to make a tutorial for a platform inside a jupyter notebook

有时候,我需要在像这样的单元中运行linux命令:

at some point I need to run a linux command inside a cell like this :

!sudo apt-get install blah

但是无法弄清楚如何输入sudo通行证,并且我不想用sudo运行jupyter笔记本,知道如何执行此操作吗?

but cant figure out how to enter the sudo pass , and I dont want to run jupyter notebook with sudo, any idea how to do this ?

更新:我检查了所有方法,所有方法都有效.

Update: I checked all the methods, all of them are working.

1:

请求密码,这实际上隐藏了用户的输入,然后运行 python中的sudo命令.

Request password using getpass module which essentially hides input by user and then run sudo command in python.

 import getpass
 import os

 password = getpass.getpass()
 command = "sudo -S apt-get update" #can be any command but don't forget -S as it enables input from stdin
 os.system('echo %s | %s' % (password, command))

2:

 import getpass
 import os

 password = getpass.getpass()
 command = "sudo -S apt-get update" # can be any command but don't forget -S as it enables input from stdin
 os.popen(command, 'w').write(password+'\n') # newline char is important otherwise prompt will wait for you to manually perform newline

注意上述方法:

您输入密码的字段可能不会出现在ipython中 笔记本.它出现在Mac的终端窗口中,我想像它 将出现在PC的命令外壳中.甚至结果详细信息也将出现在终端中.

The field where you enter the password may not appear in the ipython notebook. It appears in the terminal window on a mac, and I imagine it will appear in a command shell on a PC. Even the result details would appear in the terminal.

3:

您可以将密码存储在mypasswordfile文件中,只需输入单元格即可:

You can store your password in mypasswordfile file and just type in cell :

!sudo -S apt-get install blah < /pathto/mypasswordfile # again -S is important here

如果我想在jupyter notebook本身中查看命令的输出,我会更喜欢这种方法.

I would prefer this method if I want to view output of the command in jupyter notebook itself.

参考:

  1. 在IPython笔记本中请求密码

https://docs.python.org/3.1/library/getpass .html