linux 在jupyter notebook的单元格中使用sudo

btqmn9zl  于 5个月前  发布在  Linux
关注(0)|答案(5)|浏览(102)

我正试图为jupyter笔记本内的一个平台制作教程
在某个时候,我需要在一个单元格中运行一个Linux命令,如下所示:

!sudo apt-get install blah

字符串
但是不知道如何进入sudo通行证,我不想运行jupyter笔记本与sudo,任何想法如何做到这一点?

1cklez4t

1cklez4t1#

**更新:**我检查了所有的方法,它们都在工作。
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 notebook中查看命令的输出,我更喜欢这种方法。

参考资料:

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

kx5bkwkv2#

对于jupyter运行在localhost上的情况,我想指出另一种可能性:而不是sudo,使用**pkexec(或旧系统gksu**):

!pkexec apt-get install blah

字符串
这将要求密码在一个gui解决问题.

6fe3ivhb

6fe3ivhb3#

您可以通过{varname}语法(例如this cool blog)将python变量从notebook传递到shell,而无需导入ossubprocess模块。
如果你已经在python中定义了一个密码和命令变量(参见Suparshva的回答),那么你可以运行这个一行程序:

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

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

tag5nh1u

tag5nh1u4#

如果你不想你的密码被存储在某个地方,你可以这样写:

from getpass import getpass
!echo {getpass()} | sudo -S {command}

字符串
这也回答了伊恩·丹佛斯的问题

wztqucjr

wztqucjr5#

你可以

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

字符串
如果你想避免Python语法,你可以定义自己的单元格魔法(例如%sudo apt-get install bla)。

相关问题