python - 在 jupyter notebook 的单元格中使用 sudo

标签 python linux python-3.x ubuntu jupyter-notebook

我正在尝试为 jupyter notebook 中的平台制作教程

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

!sudo apt-get install blah

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

最佳答案

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


1:

Request password使用 getpass module它实质上隐藏了用户的输入,然后运行 ​​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

上述方法的注意事项:

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 中文件并在单元格中输入:

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

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

引用资料:

  1. Requesting password in IPython notebook

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

  3. Using sudo with Python script

关于python - 在 jupyter notebook 的单元格中使用 sudo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44996933/

相关文章:

html - 如何根据数据库用户设置文件权限

python-3.x - 我如何使用 float 在 python 的 for 循环中递增

python - 如何将具有不规则列的html代码转换为嵌套的json文件?

python - 在 Python 3 中尝试除外

python - 模块长名和短名

python - 选择所有年份都有观察值的行 python

java - 子文件夹不是通过 java 通过 scp 命令复制的

python - 使用#-*-编码: utf-8 -*- does not remove "Non-ASCII character '\x9 0' in file hello.exe on line 1, but no encoding declared" error

python - 如何获取数字列表作为输入并计算总和?

linux - 如何将 Jenkins 主目录从/var/lib 更改为 app 并为原始位置创建符号链接(symbolic link),因为工作不会受到影响