预期:如何转储子 "as is" 的所有内容?

pexpect: howto dump all content from child "as is"?

我们的 "shared" 服务器上有一些奇怪的设置,在某些情况下不会记住我的 git 密码。我努力解决真正的问题;但在某些时候我放弃并创建了这个 python 脚本:

#!/usr/bin/env python3
"""
pass4worder: a simply python script that runs a custom command; and "expects" that command to ask for a password.
The script will send a custom password - until the command comes back with EOF.
"""

import getpass
import pexpect
import sys

def main():
    if len(sys.argv) == 1:
      print("pass4worder.py ERROR: at least one argument (the command to run) is required!")
      sys.exit(1)

    command = " ".join(sys.argv[1:])
    print('Command to run: <{}>'.format(command))
    password = getpass.getpass("Enter the password to send: ")

    child = pexpect.spawn(command)
    print(child.readline)
    counter = 0

    while True:
        try:
            expectAndSendPassword(child, password)
            counter = logAndIncreaseCounter(counter)
        except pexpect.EOF:
            print("Received EOF - exiting now!")
            print(child.before)
            sys.exit(0)


def expectAndSendPassword(child, password):
    child.expect("Password .*")
    print(child.before)
    child.sendline(password)


def logAndIncreaseCounter(counter):
    print("Sent password ... count: {}".format(counter))
    return counter + 1

main()

这个解决方案可以完成工作;但我不满意那些印刷品的样子;示例:

> pass4worder.py git pull
Command to run: <git pull>
Enter the password to send: 
<bound method SpawnBase.readline of <pexpect.pty_spawn.spawn object at 0x7f6b0f5ed780>>
Received EOF - exiting now!
b'Already up-to-date.\r\n'

我更喜欢这样的东西:

Already up-to-date
Received EOF - exiting now!

换句话说:我正在寻找一种方法,让 pexect 简单地将所有内容 "as is" 打印到 stdout ...,同时仍在执行其工作。

这可能吗?

(也欢迎关于我的脚本的任何其他提示)

  1. child.readline 是一个函数所以我认为你实际上想要 print(child.readline() ).
  2. print(child.before) 更改为 print(child.before.decode() )bytes.decode()bytes (b'string') 转换为 str.