[英]pexpect: howto dump all content from child “as is”?
We have some strange setup on our "shared" server that will not remember my git password for certain situations. 我们在“共享”服务器上进行了一些奇怪的设置,在某些情况下不会记住我的git密码。 I tried hard to fix the real issue; 我努力解决了实际问题; but at some point I gave up and created this python script: 但在某个时候,我放弃了并创建了这个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()
This solution does the job; 该解决方案可以完成工作; but I am not happy about how those prints look like; 但我对这些印刷品的外观不满意; example: 例:
> 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'
I would rather prefer something like: 我更喜欢这样的东西:
Already up-to-date
Received EOF - exiting now!
In other words: I am looking for a way so that pexect simply prints everything "as is" to stdout ... while still doing its job. 换句话说:我正在寻找一种方法,使pexect可以简单地将所有内容“按原样”打印到stdout ...,同时仍然可以完成其工作。
Is that possible? 那可能吗?
(any other hints regarding my script are welcome too) (也欢迎提供有关我的脚本的其他任何提示)
child.readline
is a function so I think you actually wanted print(child.readline() )
. child.readline
是一个函数,所以我认为您实际上想要print(child.readline() )
。 print(child.before)
to print(child.before.decode() )
. 将print(child.before)
更改为print(child.before.decode() )
。 bytes.decode()
converts bytes
( b'string'
) to str
. bytes.decode()
将bytes
( b'string'
bytes.decode()
转换为str
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.