问题描述
我正在尝试为 jupyter notebook 中的平台制作教程
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 pass ,而且我不想用 sudo 运行 jupyter notebook,知道怎么做吗?
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:
请求密码 使用 getpass 模块
基本上隐藏由用户输入,然后在 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+'
') # newline char is important otherwise prompt will wait for you to manually perform newline
上述方法的注意事项:
你输入密码的字段可能不会出现在ipython中笔记本.它出现在 mac 上的终端窗口中,我想象它将出现在 PC 上的命令外壳中.甚至结果详细信息也会出现在终端中.
3:
您可以将密码存储在 mypasswordfile
文件中,然后输入单元格:
You can store your password in mypasswordfile
file and just type in cell :
!sudo -S apt-get install blah </pathto/mypasswordfile # 再次 -S 在这里很重要
如果我想在 jupyter notebook 本身中查看命令的输出,我更喜欢这种方法.
I would prefer this method if I want to view output of the command in jupyter notebook itself.
参考:
https://docs.python.org/3.1/library/getpass.html
这篇关于在 jupyter notebook 的单元格中使用 sudo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!