我正试图为jupyter笔记本中的平台制作一个教程

在某个时刻,我需要在一个单元格中运行一个linux命令,如下所示:

!sudo apt-get install blah

但是我不知道怎么进入sudo通行证,我也不想和sudo一起运行jupyter笔记本,知道怎么做吗?

推荐答案

我判断了所有的方法,所有的方法都有效.


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

NOTE for above methods:

输入密码的字段可能不会出现在ipython中

3:

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

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

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

References:

  1. 一百

  2. 一百

  3. Using sudo with Python script

Python-3.x相关问答推荐

动态范围内来自另外两列的列求和

Pandas 插入的速度太慢了.对于跟踪代码,什么是更快的替代方案?

CDKTF ec2 具有特定私有 IP 地址的娱乐

如何使用python将pdf文件的页面合并为单个垂直组合页面

从 https://www.niftytrader.in/stock-options-chart/sbin 提取 SBIN 股票最大痛苦值的 Python 代码不起作用 - 我错过了什么?

有没有办法使用 python opencv 计算与图像的白色距离

如何在python 3.10中将列表项(字符串类型)转换为模块函数

列表中的重复数字与列表理解

如何禁用 pylint 禁止自用警告?

Python 3 变量名中接受哪些 Unicode 符号?

TensorFlow:dataset.train.next_batch 是如何定义的?

使用逗号时,除了处理程序中的语法无效

Python中的依赖倒置

如何在 Python 中计算两个包含字符串的列表的 Jaccard 相似度?

如何在多核上运行 Keras?

如何在不使用 @hydra.main() 的情况下获取 Hydra 配置

用于 unicode 大写单词的 Python 正则表达式

为什么 Python 不能识别我的 utf-8 编码源文件?

将字符串拆分为最大长度 X 的片段 - 仅在空格处拆分

在 Python 中生成马尔可夫转移矩阵