python - pexpect,处理子进程
问题描述
我正在尝试自动将数据记录到托管的 oh 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通过某种方式检测到这是一项自动化任务,并且登录失败
请有人告诉我是什么问题,
解决方案
\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
祝你编码好运!
推荐阅读
- apache-flink - 动态调用 Flink 算子
- .net - 找不到元素时如何避免/忽略 OpenQA.Selenium.NoSuchElementException?
- javascript - 如何使 requestAnimationFrame 方法模块化?
- mobaxterm - Mosh 使用 MobaXterm 无法连接并出现错误,如何解决?
- c++ - 在directx11代码中更改全屏模式下的刷新率不起作用
- python - 将标量添加到图像时破坏图像像素
- django - AttributeError:“NoneType”对象没有属性“保存”django
- ruby - Ruby on rails,无法显示实例变量的内容
- python - 使用熊猫创建数据透视表
- ios - 快速获取错误的设备语言