问题描述
我正在尝试为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
注意上述方法:
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.
参考:
https://docs.python.org/3.1/library/getpass .html
这篇关于在jupyter笔记本的单元格内使用sudo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!