gpt4 book ai didi

python - pexpect:如何转储子 "as is"的所有内容?

转载 作者:行者123 更新时间:2023-12-01 03:23:56 25 4
gpt4 key购买 nike

我们的“共享”服务器上有一些奇怪的设置,在某些情况下不会记住我的 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 简单地将所有内容“按原样”打印到标准输出......同时仍然完成其工作。

这可能吗?

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

最佳答案

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

关于python - pexpect:如何转储子 "as is"的所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41613841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com