首页 > 解决方案 > pexpect,处理子进程

问题描述

我正在尝试自动将数据记录到托管的 o​​h heroku 帐户的 postgres 数据库中。

import pexpect
import os
import sys
from time import sleep

#os.system("heroku login -i")
child = pexpect.spawn ('heroku login -i')
child.expect ('Email .*:')
child.sendline ('har**********@gmail.com')
child.expect ('Password:')
child.sendline ('js4*********SZq')
child.close(force=True)
#child.send('\r')
sleep(0.5)
child2 = pexpect.spawn ('heroku pg:psql postgresql-globular-95641 --app overal-vehicle')
child2.expect ('overal-vehicle::DATABASE=>')
child2.send ('SELECT version();')
child2.send('\r')

#在这部分之后我还想添加一些sql查询,但我无法登录,它只是告诉无效凭据,并通过浏览器登录。

这就是我想要实现的终端截图

当我手动尝试时,所有命令都可以工作,我想知道可能是什么问题,或者heroku通过某种方式检测到这是一项自动化任务,并且登录失败

请有人告诉我是什么问题,

标签: pythonheroku-postgrespexpectos.system

解决方案


\r输入密码时,您必须使用老式 Pexpect 并仅发送回车符 ( ):

注意- 在 Ubuntu 20.04.3 LTS 上使用 Python 3.8.10

#!/usr/bin/python3
import pexpect

child = pexpect.spawn("heroku login -i")
child.delaybeforesend = 0.5
child.expect_exact("Email:")
child.sendline("har**********@gmail.com\r")
child.expect_exact('Password:')

# ojo!
child.send("js4*********SZq")
child.send("\r")

index = child.expect_exact(["Logged in as", pexpect.EOF, pexpect.TIMEOUT, ])
if index != 0:
    print("Could not log into Heroku.")
# The child is closed implicitly when command is complete, but I add this anyway
child.close()
print("Logged in!")

child = pexpect.spawn("heroku auth:whoami")
index = child.expect_exact(["Error: not logged in", "har**********@gmail.com", ])
if index == 0:
    print("Login failed!")
    exit()
child.close()
print("heroku auth:whoami: {0}".format(child.match.decode()))

child = pexpect.spawn("heroku logout")
child.expect_exact("Logging out... done")
child.close()
print("{0}".format(child.match.decode()))

输出

Logged in!
heroku auth:whoami: har**********@gmail.com
Logging out... done

祝你编码好运!


推荐阅读