我正在尝试为 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 本身中查看命令的输出,我会更喜欢这种方法。
引用资料:
关于python - 在 jupyter notebook 的单元格中使用 sudo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44996933/