Python - 通过终端与打开的程序对话

标签 python linux terminal communication

我一直在使用os.system()与终端进行通信,效果非常好。但是,用它我打开一个需要写入命令的程序,但我不太确定如何执行此操作。

基本上,我正在运行:

tleap -f leaprc

这将在终端中打开程序,并显示:

*non-important code*
>

现在,我需要开始向程序发送命令,但我找不到任何可以写入 > 右侧的内容。 os.system() 对此不起作用,而且,我不精通 Python,所以一无所知。

最佳答案

您可以尝试使用subprocess.Popen

这里有一些使用 python 作为程序的示例代码。

>>> p = subprocess.Popen(['python'],stdin = subprocess.PIPE,stdout = subprocess.PIPE)
>>> p.stdin.write('print "Hello, world!"\n')
>>> p.stdin.write('for i in range(10):\n    print i\n')
>>> p.communicate()
('Hello, world!\r\n0\r\n1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7\r\n8\r\n9\r\n', None)

如果您在 Linux 上运行,将命令发送到终端的最简单方法是使用 shlex.split 函数。所以你会打电话

p = subprocess.Popen(shlex.split('tleaf -f leaprc'),stdin = subprocess.PIPE,stdout = subprocess.PIPE)

至少根据我的经验,在进程对象上调用communicate会关闭它,因此您只有一次机会读取输出。如果这不适合您,我会查看 pexpect模块。

关于Python - 通过终端与打开的程序对话,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16989197/

相关文章:

java - 如何清理 Runtime.exec() 中使用的用户输入?

linux - 将更多文件的行数与文件名组合起来

regex - 使用 sed 匹配除正斜杠之外的非数字

python - 用 Celery 组合链、组和 block

python - 识别 C 项目中所有变量的类型

python - 如何使用 DEAP 定义遵循特定顺序模式的自定义遗传算法个体

linux - 如何找出自己执行的后台作业

linux - 在 Linux 上安装 RPostgreSQL

terminal - 发现错误 : No pubspec. yaml 文件。在MAC中

python - OpenCV 中使用图像矩进行字体匹配