【问题标题】:using sudo inside jupyter notebook's cell在 jupyter notebook 的单元格中使用 sudo
【发布时间】:2017-12-13 07:06:06
【问题描述】:

我正在尝试为 jupyter notebook 中的平台制作教程

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

!sudo apt-get install blah

但不知道如何输入 sudo pass,我不想用 sudo 运行 jupyter notebook,知道该怎么做吗?

【问题讨论】:

    标签: python linux python-3.x ubuntu jupyter-notebook


    【解决方案1】:

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


    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 上的命令外壳中。甚至结果详细信息也会出现在终端中。

    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

    【讨论】:

    • 如果您离开笔记本电脑,上述内容是否有变体无法访问密码?
    【解决方案2】:

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

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

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

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

    【讨论】:

      【解决方案3】:

      我想为 jupyter 在 localhost 上运行的情况指出另一种可能性:使用 pkexec 代替 sudo(或者对于旧系统 @ 987654322@):

      !pkexec apt-get install blah
      

      这将在解决问题的 gui 中询问密码...

      【讨论】:

        【解决方案4】:

        你可以

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

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

        【讨论】:

          【解决方案5】:

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

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

          附:这也回答了 Ian Danforth 的问题

          【讨论】:

            猜你喜欢
            • 2017-11-16
            • 2023-02-22
            • 1970-01-01
            • 2020-02-15
            • 1970-01-01
            • 2021-02-16
            • 1970-01-01
            • 2020-09-03
            • 2018-09-04
            相关资源
            最近更新 更多