How to launch and pass input to an external progra

2019-04-02 03:04发布

问题:

I am using Python to execute an external program. And I would also like Python to send some keystrokes to the called program to complete auto-login.

The problem is that when I used subprocess.call() to execute the external program, the program got the system focus and the Python script was not able to respond until I closed the external program.

Do you guys have any suggestion about this? Thanks a lot.

回答1:

Use subprocess.Popen() instead of .call()

With Popen you also can control stdin, stdout and stderr file descriptors, so you maybe can interact with the external program.

Silly example:

s = subprocess.Popen(command, stdout=subprocess.PIPE, 
                     stderr=subprocess.PIPE) # The script is not blocked here

# Wait to finish
while s.poll() is None: # poll() checks if process has finished without blocking
    time.sleep(1)
    ... # do something

# Another way to wait
s.wait() # This is blocking

if s.returncode == 0:
    print "Everything OK!"
else:
    print "Oh, it was an error"

Some useful methods:

Popen.poll() Check if child process has terminated. Set and return returncode attribute.

Popen.wait() Wait for child process to terminate. Set and return returncode attribute.

Popen.communicate(input=None) Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

Many more info in the docs