3

我正在学习 Python,同时将一些 bash 脚本转换为 Python shell 脚本。我还不明白的一件事是如何处理这些脚本中使用的 heredocs。以下是 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 中做这些事情?

4

2 回答 2

3

Python中的Heredoc

使用多行字符串(三引号字符串'''""")。请参阅教程中的字符串

运行命令

import subprocess
subprocess.Popen(['cat'], stdin=subprocess.PIPE).communicate('''
    Hello multiline-string
    simliar to heredoc.
''')
于 2013-07-25T09:19:47.900 回答
0

sh(以前称为 pbs)是一个成熟的 Python 子进程接口,它允许您调用任何程序,就好像它是一个函数一样:

from sh import ifconfig
print(ifconfig("wlan0"))

完整文档:http
://amoffat.github.com/sh 关注 Github:http: //github.com/amoffat/sh

它如何解决此问题的第一个问题的示例:

from sh import ssh
import os, sys

# open stdout in unbuffered mode
sys.stdout = os.fdopen(sys.stdout.fileno(), "wb", 0)

aggregated = ""
def ssh_interact(char, stdin):
    global aggregated
    sys.stdout.write(char.encode())
    aggregated += char
    if aggregated.endswith("password: "):
        stdin.put("correcthorsebatterystaple\n")

p = ssh("10.10.10.100", _out=ssh_interact, _out_bufsize=0, _tty_in=True)
p.wait()

它可以sudo这样处理:

with sudo:
    print(ls("/root"))

它有一个简洁的功能,称为 STDOUT/ERR 回调:

sh 可以使用回调以增量方式处理输出。这很像重定向:通过将参数传递给 _out 或 _err(或两者)特殊关键字参数,除了这一次,您传递一个可调用对象。将为您的命令输出的每一行(或块)数据调用此可调用对象。

最后,作为标准 Python 工具的一部分,raw_input它可以写入标准输出并从标准输入读取。这也将解决这个问题中的第二个问题。

于 2013-07-26T17:42:58.373 回答