在 jupyter notebook 的单元格中使用 sudo

新手上路,请多包涵

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

在某些时候,我需要像这样在单元格中运行 linux 命令:

 !sudo apt-get install blah

但不知道如何输入 sudo pass,我不想用 sudo 运行 jupyter notebook,知道怎么做吗?

原文由 MJ Sameri 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.3k
2 个回答

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


1:

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

  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 的命令 shell 中。甚至结果详细信息也会出现在终端中。

3:

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

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

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

参考:

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

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

  3. 在 Python 脚本中使用 sudo

原文由 รยקคгรђשค 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于 jupyter 在本地主机上运行的情况,我想指出另一种可能性:使用 pkexec (或旧系统 gksu )代替 sudo

 !pkexec apt-get install blah

这将要求在 gui 中输入密码来解决问题…

原文由 ntg 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题