python - 如何向已作为子进程打开的 CLI 发送命令?

标签 python python-2.7 ubuntu subprocess

我需要一些帮助。我想做的是用 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 

首先,我很高兴看到像 lsifconfig 这样的简单命令可以工作。只是在新终端中放置一些文本以确认其有效。

我曾希望 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/

相关文章:

python - 用户警告 : failed to import the optional _tifffile C extension module

python - 当他们收听的队列变空时,如何自动杀死 celery worker ?

python - 检测解释器在守护线程中关闭

mysql - 无法将 pandas 数据框中的列添加到 python 中的 mysql

python - 如何使用python输出颜色?

linux - 解压缩并移动下载的文件 - Linux

python - 与 Spark 交互的 REST API

python - DataLoader 不在 PyTorch 中随机采样

24小时游戏的Python实现

java - 在 Ubuntu 上安装 Java 7