【问题标题】:python execute exe file with script, enter username, password, etcpython用脚本执行exe文件,输入用户名、密码等
【发布时间】:2016-06-15 14:00:46
【问题描述】:

我想调用一个exe文件并且已经输入了参数/输入数据。

cmd = dir_path + 'file.exe do something test'
p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)

这已经很好了。如果您使用 exe 文件执行此操作,您将按 Enter 键执行下一步,即输入您的用户名。然后密码等等。现在我不知道如何在我的脚本中实现这一点,这些步骤都是我的脚本完成的。基本上我不知道如何使用 python 执行 ENTER 步骤。感谢您的帮助。

更新

现在尝试了 2 种方法(在这个问题中或在 stackoverflow 上都提到过)。

方式 1>

p = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, universal_newlines=True)
# cmd represents the path of the exe file 
p.stdin.write(username+"\n")
p.stdin.write(password+"\n")
p.sdin.close()

方式 2

p = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, universal_newlines=True)

out,err = p.communicate("\n".join([username,password,"\n"]))
# last \n should terminate the exe file and communicate should wait for the process to exit

两种方式都在一行中显示相同的输出:

用户名:密码:

通常我希望是这样的:

用户名:“进程写入的用户名+\n”
密码:“进程写入的密码+\n”

应用程序在 windows7 上运行(必须是),exe 文件在命令行中运行。

那么有没有可能这个exe不支持way1way2所以它不可能通过子进程来写或者我犯了一个重大错误?!

再次感谢您的帮助。

【问题讨论】:

标签: python pipe subprocess popen


【解决方案1】:

你快到了!

您可以执行以下操作:

import subprocess
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, shell=True)
p.communicate(input='\r')

如果有任何问题,您可能需要使用 \n 而不是 \r。 \r 是回车符,\n 是换行符。

【讨论】:

  • 嗯好的。表示通信发送终止的“\r”。但我想留在“终端”中,只需输入“虚拟”即可。
  • /r 应该模拟回车(这是一个回车键),但 /n 将是一个换行符。 /n 对你有用吗?
  • 啊好的。所以如果想在 '\r' 之后添加一个新的 cmd,我可以做另一个 p.communicate(input='some cmd') 还是需要 Popen 另一个子进程(猜猜没有意义)。
  • 表示:1. cmd = "file.exe 参数" 2. input="\r" 3. new cmd = 用户名 4. input = "\r" 等等
  • @vicR 如果cmd 接受来自其标准输入的输入,那么您可以将输入传递为:p.communicate("\n".join([username, password, etc])(将universal_newlines=True 传递给Popen(),以启用文本模式)。要模拟 Enter,请传递 '\n'
猜你喜欢
  • 2019-11-02
  • 2021-12-14
  • 1970-01-01
  • 2018-03-27
  • 2011-06-06
  • 2021-06-08
  • 1970-01-01
相关资源
最近更新 更多