python exe命令,用python调用命令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.

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.

Thanks

解决方案

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

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:

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值