我正在学习 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/