我需要一些帮助。我想做的是用 python 程序打开一个子进程,然后让子进程在程序的某些点执行特定的命令。让我尝试用一个非常简单的代码片段来说明我的问题:
import subprocess
import time
#create a new terminal
cmd = ["gnome-terminal --window &"]
process = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
#do something else
time.sleep(5)
#and now I want to execute a command in the new terminal
首先,我很高兴看到像 ls
或 ifconfig
这样的简单命令可以工作。只是在新终端中放置一些文本以确认其有效。
我曾希望 Popen.communicate(input)
能够解决问题,即类似于 process.communicate("ls")
的做法,但到目前为止好像不行。
任何帮助将不胜感激。
最佳答案
您可能想查看 pexpect 模块 - 它正是为此目的而设计的,包括查找从子流程返回的特定提示和错误。
我编写的脚本中的一个简单(精简)示例。它使用 ssh session 登录并在服务器上运行脚本。
import pexpect
server = "server.home" # normally passed as arguments
display = 1 # normally passed as arguments
ssh = pexpect.spawn("ssh", ["{0}".format(server), "~/vnc.py", "{0}".format(display)])
try:
index = ssh.expect("^.*password:")
except:
print "Have not received password prompt from {host} - server down or ssh not enabled".format(host=server)
sys.exit(1)
if index == 0:
ssh.sendline( password )
else:
print "Unable to communicate with server"
非常有用,特别是当您有复杂的交互时。
顺便说一句,完整的脚本是一组自制脚本,允许我在远程服务器上启动 VNC 服务器(作为打印服务器运行),然后将 vnc 查看器登录到 VNC 服务器上。
关于python - 如何向已作为子进程打开的 CLI 发送命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24551796/