在jupyter notebook的单元格中使用sudo

问题描述 投票:3回答:3

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

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

!sudo apt-get install blah

但无法弄清楚如何进入sudo通行证,我不想用sudo运行jupyter笔记本,任何想法如何做到这一点?

python linux python-3.x ubuntu jupyter-notebook
3个回答
10
投票

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


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

以上方法的注意事项:

输入密码的字段可能不会出现在ipython笔记本中。它出现在mac的终端窗口中,我想它会出现在PC上的命令shell中。甚至结果细节也会出现在终端中。

3:

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

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

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

参考文献:

  1. Requesting password in IPython notebook
  2. https://docs.python.org/3.1/library/getpass.html
  3. Using sudo with Python script

2
投票

您可以

subprocess.Pope(['sudo', 'apt-get', 'install', 'bla'])

如果你想避免使用python语法,你可以定义自己的单元格魔法,为你做到这一点(例如%sudo apt-get install bla)。


2
投票

您可以将python变量从笔记本传递到shell,而无需使用{varname}语法(例如os)导入subprocessthis cool blog模块。

如果您在python中定义了密码和命令变量(请参阅Suparshva的答案),那么您可以运行这个单行程序:

!echo {password}|sudo -S {command}

感叹号告诉jupyter在shell中运行它,然后echo命令将从名为password的变量中获取真实密码(例如'funkymonkey'),然后将其传输到sudo'd command变量(这是一个描述的字符串)一个shell命令,例如'apt-get update')。

© www.soinside.com 2019 - 2024. All rights reserved.