如何在python中与终端交互 [英] How to interact with a Terminal in python

查看:40
本文介绍了如何在python中与终端交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个小脚本.该脚本应打开 3 个终端并独立与这些终端交互.

I'm working on a small script. The script should open 3 terminals and interact with this terminals independently.

我非常理解子流程是做到这一点的最佳方式.到目前为止我所做的:

I am pretty understand that subprocess is the best way to do that. What I've done so far:

# /usr/bin/env python
import subprocess

term1 = subprocess.Popen(["open", "-a", "Terminal"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
term1.communicate(input="pwd")

我的问题是我无法与新终端交互.这部分 term1.communicate(input="pwd") 不起作用.我无法向新终端发送命令.我也试过 term1.communicate(input="pwd\n") 但什么也没发生

My problem is I cannot interact with a new terminal. this part term1.communicate(input="pwd") is not working. I cannot send a command to a new Terminal. I also tried term1.communicate(input="pwd\n") but nothing happens

你知道我该怎么做吗?

附言我正在使用 Mac 操作系统.

P.S. I am using Mac OS.

推荐答案

无需打开终端即可同时运行这两个命令.

You can run both commands concurrently without opening terminals.

import subprocess
process1 = subprocess.Popen(["ls", "-l"])
process2 = subprocess.Popen(["ls", "-l"])

如果您运行该代码,您将看到该目录被列出两次,交错在一起.您可以根据自己的特定需求进行扩展:

If you run that code you will see that the directory is listed twice, interleaved together. You can expand this for your specific needs:

tcprelay1 = subprocess.Popen(["tcprelay", "telnet"])
tcprelay2 = subprocess.Popen(["tcprelay", "--portoffset [arg1] [arg2]")

这篇关于如何在python中与终端交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆