python 用脚本执行exe文件,输入用户名,密码等
python execute exe file with script, enter username, password, etc
我想调用一个exe文件并且已经输入了parameters/input-data。
cmd = dir_path + 'file.exe do something test'
p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
这已经可以正常工作了。如果您使用 exe 文件执行此操作,您将按 enter 键执行下一步,即输入您的用户名。然后是密码等等。现在我不知道如何将它实现到我的脚本中,这些步骤都是我的脚本完成的。基本上我不知道如何使用 python 执行 ENTER 步骤。感谢您的帮助。
更新
现在尝试了 2 种方法(都在这个问题或 Whosebug 上的其他问题中提到)。
方式 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
两种方式都在一行中显示相同的输出:
Username: Password:
通常我希望是:
Username: "username wrote by process + \n"
Password: "password wrote by process + \n"
应用程序在 windows7 上 运行(必须是)并且 exe 文件在命令行中运行。
那么有没有可能是exe不支持way1和way2所以不可能通过子进程来写它或者我犯了一个大错误吗?!
再次感谢您的帮助。
快完成了!
您可以执行以下操作:
import subprocess
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, shell=True)
p.communicate(input='\r')
如果有任何问题,您可能需要使用 \n 而不是 \r。 \r 是回车return,\n 是换行符
我想调用一个exe文件并且已经输入了parameters/input-data。
cmd = dir_path + 'file.exe do something test'
p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
这已经可以正常工作了。如果您使用 exe 文件执行此操作,您将按 enter 键执行下一步,即输入您的用户名。然后是密码等等。现在我不知道如何将它实现到我的脚本中,这些步骤都是我的脚本完成的。基本上我不知道如何使用 python 执行 ENTER 步骤。感谢您的帮助。
更新
现在尝试了 2 种方法(都在这个问题或 Whosebug 上的其他问题中提到)。
方式 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
两种方式都在一行中显示相同的输出:
Username: Password:
通常我希望是:
Username: "username wrote by process + \n"
Password: "password wrote by process + \n"
应用程序在 windows7 上 运行(必须是)并且 exe 文件在命令行中运行。
那么有没有可能是exe不支持way1和way2所以不可能通过子进程来写它或者我犯了一个大错误吗?!
再次感谢您的帮助。
快完成了!
您可以执行以下操作:
import subprocess
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, shell=True)
p.communicate(input='\r')
如果有任何问题,您可能需要使用 \n 而不是 \r。 \r 是回车return,\n 是换行符