gpt4 book ai didi

python - 如何启动外部程序并将输入传递给外部程序

转载 作者:行者123 更新时间:2023-11-28 21:27:34 24 4
gpt4 key购买 nike

我正在使用 Python 执行外部程序。我还希望 Python 向调用的程序发送一些击键以完成自动登录。

问题是当我使用 subprocess.call() 执行外部程序时,程序获得了系统焦点并且 Python 脚本无法响应,直到我关闭外部程序。

你们对此有什么建议吗?非常感谢。

最佳答案

使用 subprocess.Popen() 而不是 .call()

使用 Popen,您还可以控制 stdinstdoutstderr 文件描述符,因此您可以进行交互与外部程序。

愚蠢的例子:

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"

一些有用的方法:

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.

更多信息 in the docs

关于python - 如何启动外部程序并将输入传递给外部程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10830372/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com