bash - 将 bash 脚本转换为 Python - 如何处理 heredocs?

标签 bash shell python

我正在学习 Python,同时将一些 bash 脚本转换为 Python shell 脚本。我还不明白的一件事是如何处理这些脚本中使用的 heredoc。以下是 bash 脚本如何使用 heredocs 的两个示例:

我需要知道如何在 Python 中做的最重要的事情是第一种情况,其中 heredoc 用于提供对命令的标准响应,因此命令可以非交互式运行:

sudo command << 'EOF'
prompt_response1
    prompt_response2
EOF

其次,像这样使用 tee 创建一个需要 sudo 权限的文件:

sudo tee /etc/xdg/autostart/updateNotificationChecker.desktop > /dev/null << 'EOF' 
[Desktop Entry]
Name=Update Notification
Exec=bash /usr/local/bin/updateNotification.sh
Terminal=false
Type=Application
NoDisplay=true
EOF

我如何在 Python 中完成这些事情?

最佳答案

Python 中的 Heredoc

使用多行字符串(三引号字符串 '''""")。参见 Strings from tutorial

运行命令

import subprocess
subprocess.Popen(['cat'], stdin=subprocess.PIPE).communicate('''
    Hello multiline-string
    simliar to heredoc.
''')

关于bash - 将 bash 脚本转换为 Python - 如何处理 heredocs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17853574/

相关文章:

shell - 在身份验证墙后面生成 PDF

scripting - 如何在Shell脚本中获取命令的打印信息

python - Django:如何将数据库中的数据以及外键实体以 JSON 形式返回给用户?

python - 基于索引列表的列表中的累积添加

bash 替换每一行中的第一个字符

linux - 逻辑上受到打击

linux - bash中带空格的回调脚本

bash - OSX bash 最小化窗口

python - 执行 'if list in list' python 的正确方法

linux - 无法在 Linux 上执行 PhantomJS