How to launch and pass input to an external program

巧了我就是萌 提交于 2019-12-21 06:04:44

问题


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



来源:https://stackoverflow.com/questions/10830372/how-to-launch-and-pass-input-to-an-external-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!