用python调用命令exe [英] Calling command exe with python

查看:148
本文介绍了用python调用命令exe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在传递参数的同时从Python运行命令exe.我看了其他一些问题,而我的问题与众不同的原因是因为我首先要在传递一些参数的同时调用cmd exe程序,然后我必须等待10秒以使exe提示我一些信息.用户名,然后输入一些密码.然后我想将此输出通过管道传输到文件.

I am trying to run a command exe from Python while passing in parameters. I have looked at a few other question, and the reason why my question is different is because I first want to call a cmd exe program while passing in some parameters, then I have to wait for 10 sec for the exe to prompt me for some username, and then some password. then I want to pipe this output out to a file.

因此,如果以前已经调用过进程,是否可以传递更多的参数? 我如何使cmd exe保持打开状态,因为一旦调用它,该进程就会死掉.

So is there a way to pass more arguments if a process is already called previously? How do I make a cmd exe stay open, because as soon as I call it, the process dies.

谢谢

推荐答案

这里是一个示例(首先,我必须创建一个简单的python应用程序,该应用程序花了一些时间来请求输入(在本示例中为6秒),称为wait.py.

Here is an example (first I had to create a simple python app that took some time to ask for input (6 seconds in this example) called wait.py

wait.py

import time

print "Sample Waiting App (waiting 6 seconds)"
time.sleep(6)
name = raw_input("Enter a Name: ")
print "Hello", name

以下是启动,等待,传递输入和读取输出的代码:

Here is the code to start, wait, pass input and read output:

automator.py

automator.py

from subprocess import Popen, PIPE, STDOUT

p = Popen(['python', 'wait.py'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
print p.communicate('Jason\n')[0]

这是正在发生的事情的分解:

And here is a break down of what is going on:

  1. subprocess.Popen()创建一个进程(运行python解释器并传递wait.py脚本作为参数)并分配给p. 最初,我使automator.py睡眠了10秒钟(给了wait.py足够的时间来清除它的计时器),但是正如@ J.F.Sebastian指出的那样,这种睡眠是不需要的.原因是对"communicate()"的调用将一直阻塞,直到wait.py完成.另外,因为wait.py是从stdin读取的,所以您实际上可以在wait.py读取stdin之前填充内容.对于从stdin流中读取的任何应用程序都是如此.
  2. 然后,字符串'Jason\n'通过p.communicate('Jason\n')[0]发送到进程,并输出输出.请注意,stdout显示的是提示符和wait.py打印语句的输出,而不是输入,这是因为输入时,输入不在stdout流中,而是在回显中. li>
  1. subprocess.Popen() creates a process (running the python interpreter and passing the wait.py script as an argument) and assigned to p. Originally I had automator.py sleep for 10 seconds (giving the wait.py enough time to clear it's timer), but as @J.F.Sebastian pointed out this sleep is unneeded. The reason is the call to 'communicate()' will block until the wait.py is finished. Also because wait.py is reading from stdin, you can actually fill stdin will content before wait.py reads it. This is true with any application that reads from the stdin stream.
  2. Then the string 'Jason\n' is sent to the process via p.communicate('Jason\n')[0] and the output is printed. Note that stdout is showing the prompt and the output of the wait.py print statement, but not the input, this is because the input isn't in the stdout stream when you type it, it's being echoed.

这篇关于用python调用命令exe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆