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
5条答案
按热度按时间1cklez4t1#
**更新:**我检查了所有的方法,它们都在工作。
1:
Request password使用
getpass module
,它本质上隐藏了用户的输入,然后运行sudo command in python。字符串
2:
型
上述方法注意事项:
输入密码的字段可能不会出现在ipython笔记本中。它出现在Mac的终端窗口中,我想它会出现在PC上的命令shell中。甚至结果细节也会出现在终端中。
3:
您可以将您的密码存储在
mypasswordfile
文件中,只需在单元格中输入:!sudo -S apt-get install blah < /pathto/mypasswordfile # again -S is important here
个如果我想在jupyter notebook中查看命令的输出,我更喜欢这种方法。
参考资料:
kx5bkwkv2#
对于jupyter运行在localhost上的情况,我想指出另一种可能性:而不是sudo,使用**pkexec(或旧系统gksu**):
字符串
这将要求密码在一个gui解决问题.
6fe3ivhb3#
您可以通过{varname}语法(例如this cool blog)将python变量从notebook传递到shell,而无需导入
os
或subprocess
模块。如果你已经在python中定义了一个密码和命令变量(参见Suparshva的回答),那么你可以运行这个一行程序:
字符串
感叹号告诉jupyter在shell中运行它,然后
echo
命令将从名为password
的变量中获取真实的密码(例如“funkymonkey”),然后将其导入sudo的command
变量(这是一个描述shell命令的字符串,例如“apt-get update”)。tag5nh1u4#
如果你不想你的密码被存储在某个地方,你可以这样写:
字符串
这也回答了伊恩·丹佛斯的问题
wztqucjr5#
你可以
字符串
如果你想避免Python语法,你可以定义自己的单元格魔法(例如
%sudo apt-get install bla
)。