简体   繁体   中英

Calling command exe with python

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:

  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 @JFSebastian 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM