【问题标题】:pexpect , handeling child processpexpect,处理子进程
【发布时间】:2021-01-08 08:59:56
【问题描述】:

我正在尝试自动将数据记录到托管的 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查询,但我无法登录,它只是告诉无效凭据,并通过浏览器登录。

这就是我想要达到的目标terminal screenshot

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

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

【问题讨论】:

    标签: python heroku-postgres pexpect os.system


    【解决方案1】:

    你必须去老派Pexpect,输入密码时只发送一个回车(\r):

    注意 - 在 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
    

    祝你编码好运!

    【讨论】:

      猜你喜欢
      • 2018-08-23
      • 2011-04-08
      • 2021-12-05
      • 2017-05-06
      • 1970-01-01
      • 2013-03-11
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多